<?php

namespace App\Http\Controllers\Api;

use App\Models\Active;
use App\Models\Bespeak;
use App\Models\BespeakCate;
use App\Models\Company;
use App\Models\Config;
use App\Models\Coupon;
use App\Models\CouponType;
use App\Models\Deposit;
use App\Models\Fixfxs;
use App\Models\Good;
use App\Models\Havecoupon;
use App\Models\Image;
use App\Models\Item;
use App\Models\Memberplan;
use App\Models\Oncustomer;
use App\Models\OncustomerRecord;
use App\Models\OncustomerTarget;
use App\Models\Onorder;
use App\Models\Order;
use App\Models\Outtime_record;
use App\Models\Pack;
use App\Models\Packorder;
use App\Models\Packrecord;
use App\Models\PreferCate;
use App\Models\Sjorder;
use App\Models\Sjrecord;
use App\Models\Store;
use App\Models\Ticket;
use App\Models\Recharge;
use App\Models\Comment;
use App\Models\NoPasswordPay;
use App\Models\HoardingInstruction;
use App\Models\Hoarding;
use App\Models\HoardingTickets;
use App\Models\RechargeRecord;
use App\Models\Companies;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\DB;
use Overtrue\EasySms\EasySms;
use SimpleSoftwareIO\QrCode\Facades\QrCode;
use SmsManager;
use aliyun\SignatureHelper;
use Carbon\Carbon;
use function Sodium\compare;


class IndexController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */

    public function get_img_info(Request $request)
    {
        if ($request->hasFile('image') && $request->file('image')->isValid()) {

            $allow_types = ['image/png', 'image/jpeg', 'image/gif'];
            if (!in_array($request->image->getMimeType(), $allow_types)) {
                return ['status' => 0, 'msg' => '图片类型不正确！'];
            }

            if ($request->image->getClientSize() > 1024 * 1024 * 6) {
                return ['status' => 0, 'msg' => '图片大小不能超过 6M！'];
            }

            $path = $request->image->store('public/images');
            //绝对路径
            $file_path = storage_path('app/') . $path;

            //上传到七牛
            qiniu_upload($file_path);

            $post_path = basename($file_path);


            $url = 'https://recognition.image.myqcloud.com/ocr/businesscard';
            $str['appid'] = 1256875924;
            $str['bucket'] = 'tencentyun';
            $str['url_list'] = ["http://image.mgtv100.com/$post_path"];
            $data = json_encode($str);
            $key = get_key();   //签名key
            $curl = curl_init();
            curl_setopt($curl, CURLOPT_TIMEOUT, 30);
            curl_setopt($curl, CURLOPT_URL, $url);
            curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
            curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
            curl_setopt($curl, CURLOPT_CUSTOMREQUEST, 'POST');
            curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
            curl_setopt($curl, CURLOPT_RETURNTRANSFER, TRUE);
            curl_setopt($curl, CURLOPT_HTTPHEADER, array(
                    'Host: recognition.image.myqcloud.com',
                    'Content-Type: application/json',
                    'Authorization: ' . $key)
            );
            $res = curl_exec($curl);
            curl_close($curl);

            return $res;

        }


    }




    public function post_image(Request $request)
    {

//        return 1;
//        $files = $request->files->all();
//        $image = array_shift($files);
//        $image = \Illuminate\Http\UploadedFile::createFromBase($image);
        $url = store_image($request->image);
        return response()->json(compact('url'));

    }


    public function test()
    {
        $appid = "1256875924";
        $bucket = "tencentyun";
        $secret_id = "AKIDqa9ZqP0bJPPGXmp5GRqHXcVFobFiFd9V";
        $secret_key = "PdmzQo0cko3MVSOGx8ESb9g4GMH6qSfm";
        $expired = time() + 2592000;
        $onceExpired = 0;
        $current = time();
        $rdm = rand();
        $userid = "0";
        $fileid = "tencentyunSignTest";

        $srcStr = 'a='.$appid.'&b='.$bucket.'&k='.$secret_id.'&e='.$expired.'&t='.$current.'&r='.$rdm.'&u='
            .$userid.'&f=';

        $srcWithFile = 'a='.$appid.'&b='.$bucket.'&k='.$secret_id.'&e='.$expired.'&t='.$current.'&r='.$rdm.'&u='
            .$userid.'&f='.$fileid;

        $srcStrOnce= 'a='.$appid.'&b='.$bucket.'&k='.$secret_id.'&e='.$onceExpired .'&t='.$current.'&r='.$rdm
            .'&u='.$userid.'&f='.$fileid;
        $signStr = base64_encode(hash_hmac('SHA1', $srcStr, $secret_key, true).$srcStr);

        $srcWithFile = base64_encode(hash_hmac('SHA1', $srcWithFile , $secret_key, true).$srcWithFile );

        $signStrOnce = base64_encode(hash_hmac('SHA1',$srcStrOnce,$secret_key, true).$srcStrOnce);

        echo $signStr."\n";

        echo $srcWithFile ."\n";

        echo $signStrOnce."\n";
    }


//性别统计数据
    public function index_mg()
    {
        $data = [
            ['value' => Oncustomer::where('sex', 1)->count(), 'name' => '男'],
            ['value' => Oncustomer::where('sex', 0)->count(), 'name' => '女']
        ];
        return $data;
    }

//最近一周销量统计数据
    public function volume_week()
    {
        $date[0]['day'] = Carbon::today()->addDays(-6)->toDateString();
        $date[1]['day'] = Carbon::today()->addDays(-5)->toDateString();
        $date[2]['day'] = Carbon::today()->addDays(-4)->toDateString();
        $date[3]['day'] = Carbon::today()->addDays(-3)->toDateString();
        $date[4]['day'] = Carbon::today()->addDays(-2)->toDateString();
        $date[5]['day'] = Carbon::today()->addDays(-1)->toDateString();
        $date[6]['day'] = Carbon::today()->toDateString();
//        return $date;die;
        $money[0]['money'] = Order::whereBetween('created_at', [$date[0]['day'], $date[1]['day']])->where('type', '!=', '5')->where('is_pay', 1)->sum('price');
        $money[1]['money'] = Order::whereBetween('created_at', [$date[1]['day'], $date[2]['day']])->where('type', '!=', '5')->where('is_pay', 1)->sum('price');
        $money[2]['money'] = Order::whereBetween('created_at', [$date[2]['day'], $date[3]['day']])->where('type', '!=', '5')->where('is_pay', 1)->sum('price');
        $money[3]['money'] = Order::whereBetween('created_at', [$date[3]['day'], $date[4]['day']])->where('type', '!=', '5')->where('is_pay', 1)->sum('price');
        $money[4]['money'] = Order::whereBetween('created_at', [$date[4]['day'], $date[5]['day']])->where('type', '!=', '5')->where('is_pay', 1)->sum('price');
        $money[5]['money'] = Order::whereBetween('created_at', [$date[5]['day'], $date[6]['day']])->where('type', '!=', '5')->where('is_pay', 1)->sum('price');
        $money[6]['money'] = Order::whereBetween('created_at', [$date[6]['day'], Carbon::now()])->where('type', '!=', '5')->sum('price');
        $data = [
            $money[0]['money'], $money[1]['money'], $money[2]['money'], $money[3]['money'], $money[4]['money'], $money[5]['money'], $money[6]['money']
        ];
        $date = [
            $date[0]['day'], $date[1]['day'], $date[2]['day'], $date[3]['day'], $date[4]['day'], $date[5]['day'], '今天'
        ];
        return compact('data', 'date');
    }

//最近一月销量统计数据
    public function volume_yue()
    {


        $date[0]['day'] = Carbon::today()->addDays(-29)->toDateString();
        $date[1]['day'] = Carbon::today()->addDays(-28)->toDateString();
        $date[2]['day'] = Carbon::today()->addDays(-27)->toDateString();
        $date[3]['day'] = Carbon::today()->addDays(-26)->toDateString();
        $date[4]['day'] = Carbon::today()->addDays(-25)->toDateString();
        $date[5]['day'] = Carbon::today()->addDays(-24)->toDateString();
        $date[6]['day'] = Carbon::today()->addDays(-23)->toDateString();
        $date[7]['day'] = Carbon::today()->addDays(-22)->toDateString();
        $date[8]['day'] = Carbon::today()->addDays(-21)->toDateString();
        $date[9]['day'] = Carbon::today()->addDays(-20)->toDateString();
        $date[10]['day'] = Carbon::today()->addDays(-19)->toDateString();
        $date[11]['day'] = Carbon::today()->addDays(-18)->toDateString();
        $date[12]['day'] = Carbon::today()->addDays(-17)->toDateString();
        $date[13]['day'] = Carbon::today()->addDays(-16)->toDateString();
        $date[14]['day'] = Carbon::today()->addDays(-15)->toDateString();
        $date[15]['day'] = Carbon::today()->addDays(-14)->toDateString();
        $date[16]['day'] = Carbon::today()->addDays(-13)->toDateString();
        $date[17]['day'] = Carbon::today()->addDays(-12)->toDateString();
        $date[18]['day'] = Carbon::today()->addDays(-11)->toDateString();
        $date[19]['day'] = Carbon::today()->addDays(-10)->toDateString();
        $date[20]['day'] = Carbon::today()->addDays(-9)->toDateString();
        $date[21]['day'] = Carbon::today()->addDays(-8)->toDateString();
        $date[22]['day'] = Carbon::today()->addDays(-7)->toDateString();
        $date[23]['day'] = Carbon::today()->addDays(-6)->toDateString();
        $date[24]['day'] = Carbon::today()->addDays(-5)->toDateString();
        $date[25]['day'] = Carbon::today()->addDays(-4)->toDateString();
        $date[26]['day'] = Carbon::today()->addDays(-3)->toDateString();
        $date[27]['day'] = Carbon::today()->addDays(-2)->toDateString();
        $date[28]['day'] = Carbon::today()->addDays(-1)->toDateString();
        $date[29]['day'] = Carbon::today()->toDateString();

        $money[0]['money'] = Order::whereBetween('created_at', [$date[0]['day'], $date[1]['day']])->where('type', '!=', '5')->where('is_pay', 1)->sum('price');
        $money[1]['money'] = Order::whereBetween('created_at', [$date[1]['day'], $date[2]['day']])->where('type', '!=', '5')->where('is_pay', 1)->sum('price');
        $money[2]['money'] = Order::whereBetween('created_at', [$date[2]['day'], $date[3]['day']])->where('type', '!=', '5')->where('is_pay', 1)->sum('price');
        $money[3]['money'] = Order::whereBetween('created_at', [$date[3]['day'], $date[4]['day']])->where('type', '!=', '5')->where('is_pay', 1)->sum('price');
        $money[4]['money'] = Order::whereBetween('created_at', [$date[4]['day'], $date[5]['day']])->where('type', '!=', '5')->where('is_pay', 1)->sum('price');
        $money[5]['money'] = Order::whereBetween('created_at', [$date[5]['day'], $date[6]['day']])->where('type', '!=', '5')->where('is_pay', 1)->sum('price');
        $money[6]['money'] = Order::whereBetween('created_at', [$date[6]['day'], $date[7]['day']])->where('type', '!=', '5')->where('is_pay', 1)->sum('price');
        $money[7]['money'] = Order::whereBetween('created_at', [$date[7]['day'], $date[8]['day']])->where('type', '!=', '5')->where('is_pay', 1)->sum('price');
        $money[8]['money'] = Order::whereBetween('created_at', [$date[8]['day'], $date[9]['day']])->where('type', '!=', '5')->where('is_pay', 1)->sum('price');
        $money[9]['money'] = Order::whereBetween('created_at', [$date[9]['day'], $date[10]['day']])->where('type', '!=', '5')->where('is_pay', 1)->sum('price');
        $money[10]['money'] = Order::whereBetween('created_at', [$date[10]['day'], $date[11]['day']])->where('type', '!=', '5')->where('is_pay', 1)->sum('price');
        $money[11]['money'] = Order::whereBetween('created_at', [$date[11]['day'], $date[12]['day']])->where('type', '!=', '5')->where('is_pay', 1)->sum('price');
        $money[12]['money'] = Order::whereBetween('created_at', [$date[12]['day'], $date[13]['day']])->where('type', '!=', '5')->where('is_pay', 1)->sum('price');
        $money[13]['money'] = Order::whereBetween('created_at', [$date[13]['day'], $date[14]['day']])->where('type', '!=', '5')->where('is_pay', 1)->sum('price');
        $money[14]['money'] = Order::whereBetween('created_at', [$date[14]['day'], $date[15]['day']])->where('type', '!=', '5')->where('is_pay', 1)->sum('price');
        $money[15]['money'] = Order::whereBetween('created_at', [$date[15]['day'], $date[16]['day']])->where('type', '!=', '5')->where('is_pay', 1)->sum('price');
        $money[16]['money'] = Order::whereBetween('created_at', [$date[16]['day'], $date[17]['day']])->where('type', '!=', '5')->where('is_pay', 1)->sum('price');
        $money[17]['money'] = Order::whereBetween('created_at', [$date[17]['day'], $date[18]['day']])->where('type', '!=', '5')->where('is_pay', 1)->sum('price');
        $money[18]['money'] = Order::whereBetween('created_at', [$date[18]['day'], $date[19]['day']])->where('type', '!=', '5')->where('is_pay', 1)->sum('price');
        $money[19]['money'] = Order::whereBetween('created_at', [$date[19]['day'], $date[20]['day']])->where('type', '!=', '5')->where('is_pay', 1)->sum('price');
        $money[20]['money'] = Order::whereBetween('created_at', [$date[20]['day'], $date[21]['day']])->where('type', '!=', '5')->where('is_pay', 1)->sum('price');
        $money[21]['money'] = Order::whereBetween('created_at', [$date[21]['day'], $date[22]['day']])->where('type', '!=', '5')->where('is_pay', 1)->sum('price');
        $money[22]['money'] = Order::whereBetween('created_at', [$date[22]['day'], $date[23]['day']])->where('type', '!=', '5')->where('is_pay', 1)->sum('price');
        $money[23]['money'] = Order::whereBetween('created_at', [$date[23]['day'], $date[24]['day']])->where('type', '!=', '5')->where('is_pay', 1)->sum('price');
        $money[24]['money'] = Order::whereBetween('created_at', [$date[24]['day'], $date[25]['day']])->where('type', '!=', '5')->where('is_pay', 1)->sum('price');
        $money[25]['money'] = Order::whereBetween('created_at', [$date[25]['day'], $date[26]['day']])->where('type', '!=', '5')->where('is_pay', 1)->sum('price');
        $money[26]['money'] = Order::whereBetween('created_at', [$date[26]['day'], $date[27]['day']])->where('type', '!=', '5')->where('is_pay', 1)->sum('price');
        $money[27]['money'] = Order::whereBetween('created_at', [$date[27]['day'], $date[28]['day']])->where('type', '!=', '5')->where('is_pay', 1)->sum('price');
        $money[28]['money'] = Order::whereBetween('created_at', [$date[28]['day'], $date[29]['day']])->where('type', '!=', '5')->where('is_pay', 1)->sum('price');
        $money[29]['money'] = Order::whereBetween('created_at', [$date[29]['day'], Carbon::now()])->where('type', '!=', '5')->sum('price');
        $data = [
            $money[0]['money'], $money[1]['money'], $money[2]['money'], $money[3]['money'], $money[4]['money'], $money[5]['money'], $money[6]['money'],
            $money[7]['money'], $money[8]['money'], $money[9]['money'], $money[10]['money'], $money[11]['money'], $money[12]['money'], $money[13]['money'],
            $money[14]['money'], $money[15]['money'], $money[16]['money'], $money[17]['money'], $money[18]['money'], $money[19]['money'], $money[20]['money'],
            $money[21]['money'], $money[22]['money'], $money[23]['money'], $money[24]['money'], $money[25]['money'], $money[26]['money'], $money[27]['money'],
            $money[28]['money'], $money[29]['money'],
        ];
        $date = [
            $date[0]['day'], $date[1]['day'], $date[2]['day'], $date[3]['day'], $date[4]['day'], $date[5]['day'], $date[6]['day'],
            $date[7]['day'], $date[8]['day'], $date[9]['day'], $date[10]['day'], $date[11]['day'], $date[12]['day'], $date[13]['day'],
            $date[14]['day'], $date[15]['day'], $date[16]['day'], $date[17]['day'], $date[18]['day'], $date[19]['day'], $date[20]['day'],
            $date[21]['day'], $date[22]['day'], $date[23]['day'], $date[24]['day'], $date[25]['day'], $date[26]['day'], $date[27]['day'],
            $date[28]['day'], '今天'
        ];
        return compact('data', 'date');
    }

//到店人员年龄段统计
    public function index_age()
    {
        $data = [
            ['value' => Oncustomer::where('birth', '<', '1970-1-1')->count(), 'name' => '70前'],
            ['value' => Oncustomer::whereBetween('birth', ['1970-1-1', '1980-1-1'])->count(), 'name' => '70-80'],
            ['value' => Oncustomer::whereBetween('birth', ['1970-1-1', '1980-1-1'])->count(), 'name' => '80-90'],
            ['value' => Oncustomer::whereBetween('birth', ['1980-1-1', '1990-1-1'])->count(), 'name' => '80-90'],
            ['value' => Oncustomer::whereBetween('birth', ['1990-1-1', '2000-1-1'])->count(), 'name' => '90-00'],
            ['value' => Oncustomer::where('birth', '>', '2000-1-1')->count(), 'name' => '00后'],
        ];
        return $data;
    }

//会员到店时间统计
    public function index_inter()
    {
        $data = [
            ['value' => OncustomerRecord::whereTime('inter_at', '<=', '10:00')->whereTime('inter_at', '>=', '00:00')->count(), 'name' => '10点前'],
            ['value' => OncustomerRecord::whereTime('inter_at', '>', '10:00')->whereTime('inter_at', '<=', '12:00')->count(), 'name' => '10-12点'],
            ['value' => OncustomerRecord::whereTime('inter_at', '>', '12:00')->whereTime('inter_at', '<=', '14:00')->count(), 'name' => '12-14点'],
            ['value' => OncustomerRecord::whereTime('inter_at', '>', '14:00')->whereTime('inter_at', '<=', '16:00')->count(), 'name' => '14-16点'],
            ['value' => OncustomerRecord::whereTime('inter_at', '>', '16:00')->whereTime('inter_at', '<=', '18:00')->count(), 'name' => '16-18点'],
            ['value' => OncustomerRecord::whereTime('inter_at', '>', '18:00')->whereTime('inter_at', '<=', '20:00')->count(), 'name' => '18-20点'],
            ['value' => OncustomerRecord::whereTime('inter_at', '>', '20:00')->whereTime('inter_at', '<=', '22:00')->count(), 'name' => '20-22点'],
            ['value' => OncustomerRecord::whereTime('inter_at', '>=', '22:00')->whereTime('inter_at', '<', '24:00')->count(), 'name' => '22点后'],

        ];
        return $data;
    }

//会员BMI变化统计
    public function bmi_record($id)
    {
        $bmis = OncustomerTarget::where('oncustomer_id', $id)->where('mbi', '!=', 'null')->get();
        $number = $bmis->count();
        $time = [];
        $data = [];
        for ($x = 0; $x <= $number - 2; $x++) {
            array_push($time, $bmis[$x]['record_at']);
        }

        for ($x = 0; $x <= $number - 2; $x++) {
            array_push($data, $bmis[$x]['mbi']);

        }


        return compact('time', 'data');
    }

//微信授权 取得openid  记录在库
    public function get_code(Request $request)
    {

        $code = $request->code;
        $appid = 'wx78417eb270be182d';
        $appsecret = '3fc7b83abd9a714e405ab7e0d64083fb';
        //调用微信授权接口，初始化
        $ch = curl_init();
        //设置选项，包括URL
        curl_setopt($ch, CURLOPT_URL, "https://api.weixin.qq.com/sns/jscode2session?appid={$appid}&secret={$appsecret}&js_code={$code}&grant_type=authorization_code");
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        //执行并获取HTML文档内容
        $output = curl_exec($ch);
        //释放curl句柄
        curl_close($ch);


        $arr = json_decode($output, true);
        $data['store_id'] = 1;
//        $data['sex'] = $request['gender'];

        $data['headimgurl'] = $request['avatarUrl'];
        $data['nickname'] = $request['nickName'];
        $data['openid'] = $arr['openid'];
        $info['openid'] = $arr['openid'];
        $customer = Oncustomer::where($info)->first();
        if (!$customer) {
            //没有该用户则新增该用户
            Oncustomer::create($data);
        } else {
            //防止用户更新头像，昵称,判断会员是否到期
            if ($customer['is_member'] == 1 && $customer['member_end'] < Carbon::now()) {
                $data['is_member'] = 0;  //不是会员了
            }
            $customer->update($data);
        }
        return $output;

    }

//得到用户信息
    public function get_sex(Request $request)
    {
        //当前用户
        $oncustomer = Oncustomer::where('openid', $request->header('openid'))->first();
        $oncustomer->password = 0;
        return json_encode(compact('oncustomer'));

    }


//判断是否完善个人信息
    public function is_perfect(Request $request)
    {
        //依据电话话号判断用户信息时候完善
        $tel = Oncustomer::where('openid', $request->header('openid'))->value('tel');
        if (isset($tel) && $tel != '') {
            return 1;
        }

    }


    //判断是否年卡用户,
    public function is_member(Request $request)
    {

        $oncustomer = Oncustomer::where('openid', $request->header('openid'))->first();
        //修改暂停申请状态
        $record = Outtime_record::where('oncustomer_id', $oncustomer['id'])->orderBy('start_at', 'desc')->first();
        if ($record && $record != '') {
            if (!$record['end_at']) {
                if (time() - strtotime($record['start_at']) > 60 * 60 * 24 * 15) {
                    $record->end_at = Carbon::parse($record['start_at'])->addDay(15);
                    $record->long = 60 * 60 * 24 * 15;
                    $record->save();
                    $oncustomer->member_end = Carbon::parse($oncustomer['member_end'])->addDay(15);
                    $oncustomer->save();
                } else {
                    $record->end_at = Carbon::now();
                    $record->long = time() - strtotime($record['start_at']);
                    $record->save();
                    $oncustomer->member_end = date("Y-m-d h:i:s", strtotime($oncustomer['member_end']) + $record->long);
                    $oncustomer->save();
                }
            }
        }
        //是会员并且没有到期
        if ($oncustomer['is_member'] == 1 && $oncustomer['member_end'] >= Carbon::now()) {
            $item['oncustomer_id'] = $oncustomer['id'];
            $item['store_id'] = 1;
            $item['inter_at'] = Carbon::now();
            $item['date'] = Carbon::today();
            OncustomerRecord::create($item);
            return 1;

        }
        //会员到期了，修改会员状态，并返回0
        if ($oncustomer['is_member'] == 1 && $oncustomer['member_end'] < Carbon::now()) {
            $oncustomer->is_member = 0;
            $oncustomer->can_ask_time = 0;
            $oncustomer->save();
            //不是会员了
            return 0;
        } else {
            //不是会员
            return 0;
        }

    }


//买门票页面
    public function buy_ticket(Request $request)
    {
        //所有包含可用于门票的优惠券id
        $ticker_coupon_id = CouponType::where('type_id', 1)->pluck('coupon_id')->toarray();
        //排出不在适用范围的优惠券
        $can_use_coupon_id = Coupon::whereIn('id', $ticker_coupon_id)->where('start_at', '<=', Carbon::now())->where('end_at', '>=', Carbon::now())->pluck('id')->toarray();
        //当前用户拥有的所有优惠券ID
        $user_coupons_id = Oncustomer::with('coupon')->where('openid', $request->header('openid'))->first()->coupon->pluck('id')->toarray();
        //两者取交集
        $ids = array_intersect($can_use_coupon_id, $user_coupons_id);
        //当前用户门票可用优惠券
        $oncustomer = Oncustomer::with(['coupon' => function ($query) use ($ids) {
            $query->orderBy('ratio','asc');
            $query->whereIn('coupon_id', $ids)->where('start_at', '<=', Carbon::now())->where('end_at', '>=', Carbon::now());
            $query->with('types');
        }])->with('company')->where('openid', $request->header('openid'))->first();
        $ticket = Ticket::where('store_id', 1)->first();

        //判断是否是公司用户
        if (isset($oncustomer['company']) && $oncustomer['company'] != '' &&
            $oncustomer['company']['end_at'] > Carbon::now() && $oncustomer['company']['money'] > $ticket['price']) {
            $json = 1;
        } else {
            $json = 0;
        }
        return json_encode(compact('oncustomer', 'ticket', 'json'));


    }

//购买商品页面
    public function buy_good($id)
    {
        //所扫码商品
        $good = Good::find($id);
        return json_encode(compact('good'));
    }







//发送手机验证码
//password：'zhouleizhoulei'
    function sendSms(Request $request)
    {

        $params = array();

        // *** 需用户填写部分 ***

        // fixme 必填: 请参阅 https://ak-console.aliyun.com/ 取得您的AK信息
        $accessKeyId = "LTAIIGvSqCa9rcoG";
        $accessKeySecret = "pLgAQBrebecCD4VTLqTihVpFcz0Y5y";

        // fixme 必填: 短信接收号码
        $params["PhoneNumbers"] = $request->number;


        // fixme 必填: 短信签名，应严格按"签名名称"填写，请参考: https://dysms.console.aliyun.com/dysms.htm#/develop/sign
        $params["SignName"] = "质能站";

        // fixme 必填: 短信模板Code，应严格按"模板CODE"填写, 请参考: https://dysms.console.aliyun.com/dysms.htm#/develop/template
        $params["TemplateCode"] = "SMS_151770303";
        $rand = rand(1000, 9999);
        // fixme 可选: 设置模板参数, 假如模板中存在变量需要替换则为必填项
        $params['TemplateParam'] = Array(
            "code" => $rand,

        );
        // *** 需用户填写部分结束, 以下代码若无必要无需更改 ***
        if (!empty($params["TemplateParam"]) && is_array($params["TemplateParam"])) {
            $params["TemplateParam"] = json_encode($params["TemplateParam"], JSON_UNESCAPED_UNICODE);
        }
        // 初始化SignatureHelper实例用于设置参数，签名以及发送请求
        // 此处可能会抛出异常，注意catch
        if ($request->password == 'zhouleizhoulei') {
            $params = $this->request(
                $accessKeyId,
                $accessKeySecret,
                "dysmsapi.aliyuncs.com",
                array_merge($params, array(
                    "RegionId" => "cn-hangzhou",
                    "Action" => "SendSms",
                    "Version" => "2017-05-25",
                ))
            // fixme 选填: 启用https
            // ,true
            );

            return $rand;
        }
    }

//完善客户信息
    public function addinfo(Request $request)
    {
//验证密码，确认密码是否一致
        //if ($request->password == $request->password_re) {
//            $oncustomer = Oncustomer
            $oncustomer = Oncustomer::where('openid', $request->header('openid'))->first();
            $hasTel=Oncustomer::where('tel', $request->tel)->first();
            if($hasTel){
                return 2;
            }else{
                $oncustomer->tel = $request->tel;
                $oncustomer->name = $request->name;
                $oncustomer->sex = $request->sex;
                $oncustomer->birth = $request->birth;
                $oncustomer->age=Carbon::parse("$request->birth")->diffInYears();
                //$oncustomer->password = $request->password;
                $oncustomer->save();
//自动奖励一张，只能用于门票的优惠券
                $coupons_can_id = CouponType::where('type_id', 1)->pluck('coupon_id')->toarray();
                //优惠券能且只能用在门票
                $coupon_id = Coupon::whereIn('id', $coupons_can_id)->withCount('types')->get()->where('types_count', 1)->first()->id;
                $coupon = Havecoupon::where('oncustomer_id', $oncustomer['id'])->where('coupon_id', $coupon_id)->first();
                //防止重复奖励
                if (!$coupon) {
                    $info['is_can'] = 1;
                    $info['oncustomer_id'] = $oncustomer['id'];
                    $info['coupon_id'] = $coupon_id;
                    Havecoupon::create($info);
                }
                return 1;

            }

       // }
    }

//修改密码
    public function update_password(Request $request)
    {
        //验证验证码是否正确
        if ($request->rand == $request->write && $request->password == $request->password_re) {
            $oncustomer = Oncustomer::where('openid', $request->header('openid'))->first();
            $info['password'] = $request->password;
            $oncustomer->update($info);
            return 1;
        }

    }

//暂停年卡
    public function timeout_member(Request $request)
    {
        //申请暂停年卡
        $oncustomer = Oncustomer::where('openid', $request->header('openid'))->first();
        if ($oncustomer['is_member'] == 0) {
            return 0;  //年卡已到期
        }
        $ask_number = Outtime_record::whereBetween('start_at', [$oncustomer['member_start'], $oncustomer['member_end']])->count();

        if ($ask_number >= $oncustomer['can_ask_time']) {
            return 2;  //申请次数已用完
        } else {
            $info['start_at'] = Carbon::now();
            $info['oncustomer_id'] = $oncustomer['id'];
            Outtime_record::create($info);
            return 1;  //申请成功

        }


    }


//判断是否有没有点下课的课
    public function is_studying(Request $request)
    {
        //当前课程订单的最近一次课程记录
        $record = Sjrecord::where('sjorder_id', $request->sjorder_id)->orderBy('inter_at', 'desc')->first();
        //防止一次课程记录都没有的情况
        if (isset($record) && $record != '') {
            $time = time() - strtotime($record['inter_at']);
            $fen = floor($time / 60);      //往小取整数
            $miao = $time % 60;                    //取余数
            //已经点了下课
            if (isset($record['out_at']) && $record['out_at'] != '') {
                return 0;     //没有正在上的课
            } else {
                // 还没有点下课，返回已经上课时间
                return json_encode(compact('fen', 'miao', 'record')); //有课正在上，还没有点下课
            }
        } else {
            return 0;
        }


    }

//上下课记录操作
    public function get_course_record(Request $request)
    {
        //上课
        if ($request['type'] == 1) {

            $course = Sjorder::with('bespeakcate')->with('bespeak')->find($request->sjorder_id);
            //以上课程数
            $done = Sjrecord::where('sjorder_id', $request->sjorder_id)->sum('course_number');
            //未上课程数
            $todo = $course['bespeak']['course_number'] + $course['bespeak']['add_number'] - $done;
            //判断课程是否足够
            if ($done >= $todo) {
                return 3;
            }
            //生成上课记录
            $info['sjorder_id'] = $request->sjorder_id;
            $info['inter_at'] = Carbon::now();
            Sjrecord::create($info);
            return 1;
        }
        //下课
        if ($request['type'] == 2) {
            $record = Sjrecord::with('sjorder.bespeak')->where('sjorder_id', $request->sjorder_id)->orderBy('inter_at', 'desc')->first();
            $info['sjorder_id'] = $request->sjorder_id;
            $info['out_at'] = Carbon::now();
            $info['long'] = ceil((strtotime($info['out_at']) - strtotime($record['inter_at'])) / 60);

            if ($info['long'] > 10) {
                //10分钟缓冲时间
                $js_time = $info['long'] - 10;
                $info['course_number'] = ceil($js_time / $record['sjorder']['bespeak']['course_time']);   //向上取整
            } else {
                $info['course_number'] = 1;
            }
            //更新下课时间，课程数，课程时长
            $record->update($info);
            return json_encode(compact('record'));
        }

    }


    public function can_inter(Request $request)
    {
        $oncustomer = Oncustomer::where('openid', $request->header('openid'))->first();
        $record = OncustomerRecord::where('oncustomer_id', $oncustomer['id'])->orderBy('inter_at', 'desc')->first();

    }

//判断最近一次有没有开始计时
    public function is_instore(Request $request)
    {
        $oncustomer = Oncustomer::where('openid', $request->header('openid'))->first();
        //最近一条进门记录
        $record = OncustomerRecord::where('oncustomer_id', $oncustomer['id'])->orderBy('inter_at', 'desc')->first();
        //防止一次都没有进门
        if (isset($record) && $record != 'null') {
            $time = time() - strtotime($record['inter_at']);
            $fen = floor($time / 60);
            $miao = $time % 60;
            //在店里，还没有出去,继续计时
            if (!$record['out_at'] && time() - strtotime($record['inter_at']) <= 60 * 60 * 12) {
                $type = 0;
                return json_encode(compact('fen', 'miao', 'type'));
            }
            //超过12小时未扫码出门，自动记录出门时间，需重新购买门票
            if (!$record['out_at'] && time() - strtotime($record['inter_at']) > 60 * 60 * 12) {
                $type = 1;
                $data['out_at'] = Carbon::now();
                $time = time() - strtotime($record['inter_at']);
                $data['long'] = 720;
                $info['is_in'] = 0;
                $info['company_in'] = 0;
                DB::transaction(function () use ($data, $info, $oncustomer, $record) {
                    $oncustomer->update($info);
                    $record->update($data);

                });
                return json_encode(compact('type'));
            }
            //已经出门，需重新购买门票
            if (isset($record['out_at']) && $record['out_at'] != '') {
                $type = 1; //之前没有计时，从0开始。
                return json_encode(compact('type'));
            }
        } else {
            //第一次到店，需购买门票
            $type = 1;
            return json_encode(compact('type'));
        }

    }

    //扫码出门
    public function get_outinfo(Request $request)
    {
        if ($request['type'] == 1) {
            $oncustomer = Oncustomer::where('openid', $request->header('openid'))->first();
            $record = OncustomerRecord::where('oncustomer_id', $oncustomer['id'])->orderBy('inter_at', 'desc')->first();

            if (isset($record) && $record != '' && $record['out_at'] == '') {

                $data['out_at'] = Carbon::now();
                $time = time() - strtotime($record['inter_at']);
                $data['long'] = ceil($time / 60);
                $info['is_in'] = 0;
                $info['company_in'] = 0;

//关门自动结束上课
                $sjorder_id = Sjorder::where('oncustomer_id', $oncustomer['id'])->pluck('id')->toarray();
                $study_records = Sjrecord::with('sjorder')->whereIn('sjorder_id', $sjorder_id)->where('course_number', 0)->get();
                foreach ($study_records as $r) {
                    $r['out_at'] = Carbon::now();
                    $time = time() - strtotime($r['inter_at']);
                    $r['long'] = ceil($time / 60);
                    if ($r['long'] > 10) {
                        $js_time = $r['long'] - 10;
                        $r['course_number'] = ceil($js_time / $r['sjorder']['bespeak']['course_time']);   //向上取整
                    } else {
                        $r['course_number'] = 1;
                    }
                    $r->save();
                }


                DB::transaction(function () use ($data, $info, $oncustomer, $record) {
                    $oncustomer->update($info);
                    $record->update($data);

                });
                //todo:硬件开门
//                $this->openlock();
                return 1;


            }

        }

    }

//企业用户认证
    public function join_company(Request $request)
    {

        $name = $request->name;
        $company = Company::where('name', $name)->first();
        //公司不存在
        if (!$company) {
            return 2;
        }
        //执行绑定
        if ($request->key == $company['key']) {
            $info['company_id'] = $company['id'];
            //当前用户
            $oncustomer = Oncustomer::where('openid', $request->header('openid'))->first();
            $company_id=$oncustomer['company_id'];
            $result=$oncustomer->update($info);
            if($result){
                //修改认证人数
                if($company_id==0){
                    $selectPeople=Companies::where('name',$name)->first();
                    $updatePeople=Companies::where('name',$name)->update(['rzpeople'=>$selectPeople['rzpeople']+1]);
                }
            }
            return 1;
        } else {
            //秘钥不正确
            return 3;
        }



    }


    const APPID = 'wx78417eb270be182d';
    const SECRET = '3fc7b83abd9a714e405ab7e0d64083fb';
    const MCHID = '1515676261';
    const KEY = 'abcdzhao1234abcdabcdabcdabcdling';
    const UNURL = 'https://api.mch.weixin.qq.com/pay/unifiedorder';

    //未扫码首页
    public function index_no(Request $request)
    {
        $oncustomer = Oncustomer::where('openid', $request->header('openid'))->first();
        $data['oncustomer_id'] = $oncustomer['id'];
        $data['store_id'] = 1;
        //活跃天数，去除重复值，一天只计算一次
        $active_day = OncustomerRecord::where($data)->distinct('date')->count('date');
        //运动总分钟数
        $sport_total = OncustomerRecord::where($data)->sum('long');
        //有效打卡数，去除重复值，一天只计算一次
        $valid_day = OncustomerRecord::where($data)->where('long', '>', 30)->distinct('date')->count('date');
        //一个星期前
        $beforeweektime = Carbon::now()->addWeeks(-1)->toDateString();
        //上个星期至今日到店日
        $selected_days = OncustomerRecord::where($data)->whereBetween('inter_at', [$beforeweektime, Carbon::now()])->distinct('date')->pluck('date')->toarray();
        $date[0] = Carbon::today()->addDays(-7);
        $date[1] = Carbon::today()->addDays(-6);
        $date[2] = Carbon::today()->addDays(-5);
        $date[3] = Carbon::today()->addDays(-4);
        $date[4] = Carbon::today()->addDays(-3);
        $date[5] = Carbon::today()->addDays(-2);
        $date[6] = Carbon::today()->addDays(-1);
        $date[7] = Carbon::today();
        $date[8] = Carbon::today()->addDays(1);
        $date[9] = Carbon::today()->addDays(2);
        $date[10] = Carbon::today()->addDays(3);
        $date[11] = Carbon::today()->addDays(4);
        $date[12] = Carbon::today()->addDays(5);
        $date[13] = Carbon::today()->addDays(6);
        //上星期至今日每天打卡分钟数
        $minute[0] = OncustomerRecord::where('oncustomer_id',$oncustomer['id'])->where('date',$date[0])->sum('long');
        $minute[1] = OncustomerRecord::where('oncustomer_id',$oncustomer['id'])->where('date',$date[1])->sum('long');
        $minute[2] = OncustomerRecord::where('oncustomer_id',$oncustomer['id'])->where('date',$date[2])->sum('long');
        $minute[3] = OncustomerRecord::where('oncustomer_id',$oncustomer['id'])->where('date',$date[3])->sum('long');
        $minute[4] = OncustomerRecord::where('oncustomer_id',$oncustomer['id'])->where('date',$date[4])->sum('long');
        $minute[5] = OncustomerRecord::where('oncustomer_id',$oncustomer['id'])->where('date',$date[5])->sum('long');
        $minute[6] = OncustomerRecord::where('oncustomer_id',$oncustomer['id'])->where('date',$date[6])->sum('long');
        $minute[7] = OncustomerRecord::where('oncustomer_id',$oncustomer['id'])->where('date',$date[7])->sum('long');

        return json_encode(compact('active_day', 'sport_total', 'valid_day', 'selected_days', 'date','minute'));


    }

//单天日历详情
    public function day_show(Request $request)
    {
        $oncustomer = Oncustomer::where('openid', $request->header('openid'))->first();
        $day = $request->day;
        $date[0]['day'] = Carbon::parse($day)->addDays(-6);
        $date[1]['day'] = Carbon::parse($day)->addDays(-5);
        $date[2]['day'] = Carbon::parse($day)->addDays(-4);
        $date[3]['day'] = Carbon::parse($day)->addDays(-3);
        $date[4]['day'] = Carbon::parse($day)->addDays(-2);
        $date[5]['day'] = Carbon::parse($day)->addDays(-1);
        $date[6]['day'] = Carbon::parse($day);

        $date[0]['long'] = OncustomerRecord::where('oncustomer_id', $oncustomer['id'])->where('date', $date[0]['day'])->sum('long');
        $date[1]['long'] = OncustomerRecord::where('oncustomer_id', $oncustomer['id'])->where('date', $date[1]['day'])->sum('long');
        $date[2]['long'] = OncustomerRecord::where('oncustomer_id', $oncustomer['id'])->where('date', $date[2]['day'])->sum('long');
        $date[3]['long'] = OncustomerRecord::where('oncustomer_id', $oncustomer['id'])->where('date', $date[3]['day'])->sum('long');
        $date[4]['long'] = OncustomerRecord::where('oncustomer_id', $oncustomer['id'])->where('date', $date[4]['day'])->sum('long');
        $date[5]['long'] = OncustomerRecord::where('oncustomer_id', $oncustomer['id'])->where('date', $date[5]['day'])->sum('long');
        $date[6]['long'] = OncustomerRecord::where('oncustomer_id', $oncustomer['id'])->where('date', $date[6]['day'])->sum('long');
        $total = $date[6]['long'];
        //当天课程ID
        $siorder_ids = Sjorder::where('oncustomer_id', $oncustomer['id'])->pluck('id')->toarray();
        //当天课程
        $courses = Sjrecord::with('sjorder')->whereBetween('inter_at', [Carbon::parse($day), Carbon::parse($day)->addDays(1)])
            ->whereIn('sjorder_id', $siorder_ids)->get();
        //当天到店记录
        $record = OncustomerRecord::where('oncustomer_id', $oncustomer['id'])->where('date', Carbon::parse($day))->first();

        return json_encode(compact('date', 'total', 'courses', 'record'));


    }


//活动列表
    public function active_list()
    {

        $lists = Active::where('store_id', 1)->orderBy('created_at', 'desc')->get();
        return json_encode(compact('lists'));
    }

//活动详情
    public function active_show($id)
    {
        //活动关联优惠券，优惠券使用范围
        $list = Active::with('coupon.types')->find($id);

        return json_encode(compact('list'));
    }

    //用户详情页
    public function user_info(Request $request)
    {
        $oncustomer = Oncustomer::where('openid', $request->header('openid'))->first();
        $id = $oncustomer['id'];
        //未使用的优惠券
        $oncustomer = Oncustomer::with(['coupon' => function ($query) {
            $query->where('is_can', 1);
        }])->find($id);
        if ($oncustomer->coupon->isEmpty()) {
            //有优惠券
            $oncustomer['type'] = 0;
        } else {
            $oncustomer['type'] = 1;
        }
        return json_encode(compact('oncustomer'));
    }

    //用户拥有的优惠券
    public function user_coupons(Request $request)
    {
        $oncustomer = Oncustomer::where('openid', $request->header('openid'))->first();
        $ticker_coupon_id = CouponType::pluck('coupon_id')->toarray();
        $can_use_coupon_id = Coupon::whereIn('id', $ticker_coupon_id)->pluck('id')->toarray();
        $user_coupons_id = Oncustomer::with('coupon')->find($oncustomer['id'])->coupon->pluck('id')->toarray();

        $ids = array_intersect($can_use_coupon_id, $user_coupons_id);

        $coupons = Oncustomer::with(['coupon' => function ($query) use ($ids) {
            $query->whereIn('coupon_id', $ids);
            //$query->where('is_can', 1);
            $query->with('types');
        }])->find($oncustomer['id'])->coupon;
        return json_encode(compact('coupons'));

    }

//门店信息
    public function store($id)
    {
        $id = 1;
        $store = Store::find($id);
        $recordIds=OncustomerRecord::where('date',Carbon::today())->where('out_at',null)->distinct('oncustomer_id')->pluck('oncustomer_id');
        $man=Oncustomer::whereIn('id',$recordIds)->where('sex',1)->count();
        $woman=Oncustomer::whereIn('id',$recordIds)->where('sex',0)->count();
        //$man = Oncustomer::where('sex', 1)->where('is_in', 1)->count();
        //$woman = Oncustomer::where('sex', 0)->where('is_in', 1)->count();

        return json_encode(compact('store', 'man', 'woman'));

    }

//挑战列表
    public function packlist(Request $request)
    {
        //挑战列表
        $packs = Pack::withCount('packorder')->orderBy('sort')->get();
        //用户参加过的不重复套餐
        $oncustomer = Oncustomer::where('openid', $request->header('openid'))->first();
        $data['oncustomer_id'] = $oncustomer['id'];
        $done_ids = Packorder::where($data)->distinct('pack_id')->pluck('pack_id')->toarray();


        return json_encode(compact('packs', 'done_ids'));

    }

    //当前用户当前挑战的记录
    public function self_packlist(Request $request, $id)
    {
        $oncustomer = Oncustomer::where('openid', $request->header('openid'))->first();
        $data['pack_id'] = $id;
        $data['oncustomer_id'] = $oncustomer['id'];

        $lists = Packorder::with('pack')->where($data)->orderBy('end_at', 'desc')->get();

        return json_encode(compact('lists'));

    }

    //单次挑战记录详情s
    public function pack_record(Request $request)
    {
        $pack_id = $request->pack_id;
        $id = $request->id;
        $pack_records = Packorder::with(['packrecords' => function ($query) {
            $query->orderBy('id', 'desc');
        }])->with('pack')->find($id);
        $pack_orders = Packorder::with('oncustomer')->where('pack_id', $pack_id)->orderBy('sport_total', 'desc')->get();
        return json_encode(compact('pack_records', 'pack_orders'));


    }


    //挑战详情
    public function packshow($id)
    {
        $pack = Pack::find($id);
        return json_encode(compact('pack'));
    }

//电子档案详情
    public function user_records(Request $request)
    {
        $oncustomer = Oncustomer::where('openid', $request->header('openid'))->first();
        $data['oncustomer_id'] = $oncustomer['id'];
        $mbis = OncustomerTarget::where($data)->where('mbi', '!=', 'null')->orderBy('record_at')->get();
        $xws = OncustomerTarget::where($data)->where('xw', '!=', 'null')->orderBy('record_at')->get();
        $yws = OncustomerTarget::where($data)->where('yw', '!=', 'null')->orderBy('record_at')->get();
        $tws = OncustomerTarget::where($data)->where('tw', '!=', 'null')->orderBy('record_at')->get();
        $sgs = OncustomerTarget::where($data)->where('sg', '!=', 'null')->orderBy('record_at')->get();
        $tzs = OncustomerTarget::where($data)->where('tz', '!=', 'null')->orderBy('record_at')->get();
        return json_encode(compact('mbis', 'xws', 'yws', 'tws', 'sgs', 'tzs'));
    }


    //教练详情
    public function coach_show()
    {
        $coach = Fixfxs::with('tags')->where('is_use', 1)->get();
        return json_encode(compact('coach'));

    }

    //我的课程（私教）
    public function my_course(Request $request)
    {
        $oncustomer = Oncustomer::where('openid', $request->header('openid'))->first();
        $data['oncustomer_id'] = $oncustomer['id'];
        $data['is_pay'] = 1;
        $courses = Sjorder::where($data)->with('bespeakcate')->with('bespeak')->get();
        return json_encode(compact('courses'));
    }

//课程详情
    public function course_show($id)
    {
        //当前课程
        $course = Sjorder::with('bespeakcate')->with('bespeak')->find($id);
        //以上课程数
        $done = Sjrecord::where('sjorder_id', $id)->sum('course_number');
        //未上课程数
        $todo = $course['bespeak']['course_number'] + $course['bespeak']['add_number'] - $done;
        return json_encode(compact('course', 'done', 'todo'));
    }

    //上课记录
    public function course_record($id)
    {

        $records = Sjorder::with('sjrecords')->find($id);
        return $records;


    }


//私教规格详情
    public function format(Request $request)
    {
        $oncustomer = Oncustomer::where('openid', $request->header('openid'))->first();
        //当前私教所有规格
        $formats = Bespeak::where('is_use', 1)->orderBy('sort')->get();
        //组装价格
        $ticker_coupon_id = CouponType::where('type_id', 2)->pluck('coupon_id')->toarray();

        $can_use_coupon_id = Coupon::whereIn('id', $ticker_coupon_id)->where('start_at', '<=', Carbon::now())->where('end_at', '>=', Carbon::now())->pluck('id')->toarray();

        $user_coupons_id = Oncustomer::with('coupon')->where('openid', $request->header('openid'))->first()->coupon->pluck('id')->toarray();

        $ids = array_intersect($can_use_coupon_id, $user_coupons_id);

        $coupons = Oncustomer::with(['coupon' => function ($query) use ($ids) {
            $query->whereIn('coupon_id', $ids)->where('is_can', 1);
            $query->with('types');
        }])->find($oncustomer['id'])->coupon;
//        return $coupons;die;

        return json_encode(compact('formats', 'coupons'));
    }

    //充值页面
    public function diposit_show(Request $request)
    {
        $oncustomer = Oncustomer::where('openid', $request->header('openid'))->first();
        $oncustomer_id = $oncustomer['id'];
        $card_money = Oncustomer::find($oncustomer_id)->card_money;
        return json_encode(compact('card_money'));
    }

    //订单列表页面
    public function order_list(Request $request)
    {
        $oncustomer = Oncustomer::where('openid', $request->header('openid'))->first();
        $id = $oncustomer['id'];
        $oncustomer = Oncustomer::find($id);
        $orders = Order::with('fixfxs')->where('oncustomer_id', $id)->orderBy('pay_at', 'desc')->where('is_pay', 1)->get();
        $order_today = Order::with('fixfxs')->where('oncustomer_id', $id)->whereBetween('pay_at', [Carbon::today(), Carbon::now()])->orderBy('pay_at', 'desc')->where('is_pay', 1)->get();

        return json_encode(compact('oncustomer', 'orders', 'order_today'));

    }

//年卡页面
    public function member_plan(Request $request)
    {
        $plans = Memberplan::orderBy('sort')->get();
        return json_encode(compact('plans'));

    }

//年卡下单页面
    public function member_plan_show($id)
    {
        $plan = Memberplan::find($id);
        return json_encode(compact('plan'));

    }
//购买年卡操作


//最早购买日期
    public function first_date(Request $request)
    {
        $oncustomer = Oncustomer::where('openid', $request->header('openid'))->first();
        $date = Order::where('oncustomer_id', $oncustomer['id'])->where('is_pay', 1)->orderBy('pay_at')->first()->pay_at;
        return $date;

    }

//日期搜索订单
    public function choose_date_order(Request $request)
    {
        $oncustomer = Oncustomer::where('openid', $request->header('openid'))->first();
        $order_day = Order::with('fixfxs')->where('oncustomer_id', $oncustomer['id'])
            ->whereBetween('pay_at', [Carbon::parse($request->date), Carbon::parse($request->date)->addDay(1)])
            ->where('is_pay', 1)->orderBy('pay_at', 'desc')->get();
        $total = round($order_day->sum('price'), 2);
        $rel_total = round($order_day->where('pay_way', '!=', '4')->sum('price'), 2);

        return json_encode(compact('order_day', 'total', 'rel_total'));

    }


    //挑战下单页
    public function buy_pack($id)
    {
        $pack = Pack::find($id);
        return json_encode(compact('pack'));
    }

//记录身体指标
    public function get_target(Request $request)
    {
        $type = $request->type;
        $number = $request->number;
        $oncustomer = Oncustomer::where('openid', $request->header('openid'))->first();
        $data['oncustomer_id'] = $oncustomer['id'];
        $data['record_at'] = date("Y-m-d H:i:s", time());
//        if($type==1){
//            $data['mbi']=$number;
//            OncustomerTarget::create($data);
//            return 1;
//        }
        if ($type == 2) {
            $data['xw'] = $number;
            OncustomerTarget::create($data);
            return 1;
        }
        if ($type == 3) {
            $data['yw'] = $number;
            OncustomerTarget::create($data);
            return 1;
        }
        if ($type == 4) {
            $data['tw'] = $number;
            OncustomerTarget::create($data);
            return 1;
        }
        //当记录身高时，根据最近一次体重，自动记录BMI
        if ($type == 5) {
            $data['sg'] = $number;
            $tz = OncustomerTarget::where('tz', '!=', 'null')->orderBy('record_at', 'desc')->first()->tz;

            $data['mbi'] = $tz / $number / $number * 10000;
            OncustomerTarget::create($data);
            return 1;
        }
        //当记录体重时时，根据最近一次身高，自动记录BMI
        if ($type == 6) {
            $data['tz'] = $number;
            $sg = OncustomerTarget::where('sg', '!=', 'null')->orderBy('record_at', 'desc')->first()->sg;
            $data['mbi'] = $number / $sg / $sg * 10000;
            OncustomerTarget::create($data);
            return 1;
        }


    }


    public function index_cates()
    {
        $cates = BespeakCate::with('bespeak')->orderBy('sort')->get();
        return json_encode(compact('cates'));
    }


//优惠活动页
    public function prefer(Request $request)
    {
        $oncustomer_id = Oncustomer::where('openid', $request->header('openid'))->value('id');
        if ($oncustomer_id) {
            $have_couponid = Havecoupon::where('oncustomer_id', $oncustomer_id)->pluck('coupon_id')->toarray();
        }
        $coupons = Coupon::orderBy('sort')->limit(3)->where('is_use', 1)->get();
        $cates = PreferCate::with(['packs' =>
            function ($query) {
                $query->where('is_use', 1);
            }])
            ->orderBy('sort')->get();
        return json_encode(compact('coupons', 'cates', 'have_couponid'));
    }

    public function prefer_pack($id)
    {

        $pack = Pack::where('id', $id)->with('item')->first();
        return json_encode(compact('pack'));
    }

//领取优惠券
    public function get_coupon(Request $request, $id)
    {
        $oncustomer_id = Oncustomer::where('openid', $request->header('openid'))->value('id');
        if ($oncustomer_id) {
            $data['oncustomer_id'] = $oncustomer_id;
            $data['coupon_id'] = $id;
            $info = Havecoupon::where($data)->first();
            if ($info) {
                return 0;
            } else {
                Havecoupon::create($data);
                return 1;
            }
        }


    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    //个人页
    public function info(Request $request)
    {

        $id = Oncustomer::where('openid', $request->header('openid'))->value('id');
        $data['oncustomer_id'] = $id;
        //预约订单
        $bespeakorders = Onorder::where($data)->where('type', 1)->with('fixfxs')->with('bespeak')->orderBy('created_at')->get();
        //活动套餐
        $packorders = Onorder::where($data)->where('type', 0)->where('is_pay', 1)->with('pack.pcates')->with('item')->orderBy('created_at')->get();
        //没有使用的预约订单
        $no_use_peak = Onorder::where($data)->where('type', 1)->where('statu', 0)->with('fixfxs')->with('bespeak')->orderBy('created_at')->get();
        //已经使用的预约订单
        $use_peak = Onorder::where($data)->where('type', 1)->where('statu', 1)->with('fixfxs')->with('bespeak')->orderBy('created_at')->get();
        //没有使用的活动套餐
        $no_use_pack = Onorder::where($data)->where('type', 0)->where('is_pay', 1)->where('statu', 0)->with('pack.pcates')->with('item')->orderBy('created_at')->get();
        //已经使用的活动套餐
        $use_pack = Onorder::where($data)->where('type', 0)->where('is_pay', 1)->where('statu', 1)->with('pack.pcates')->with('item')->orderBy('created_at')->get();
        return json_encode(compact('bespeakorders', 'packorders', 'no_use_peak', 'use_peak', 'no_use_pack', 'use_pack'));
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request $request
     * @return \Illuminate\Http\Response
     */
    //当前用户拥有的优惠券
    public function info_coupon(Request $request)
    {
        $id = Oncustomer::where('openid', $request->header('openid'))->value('id');
        $coupon_id = Havecoupon::where('oncustomer_id', $id)->pluck('coupon_id')->toarray();
        $coupons = Coupon::whereIn('id', $coupon_id)->orderBy('del', 'desc')->get();
        return json_encode(compact('coupons'));
    }

    /**
     * Display the specified resource.
     *
     * @param  int $id
     * @return \Illuminate\Http\Response
     */
    //查看卷码页
    public function info_number($id)
    {
        $order = Onorder::find($id);
        return json_encode(compact('order'));
    }


    //预约
    public function bespeak_order(Request $request)
    {
        $oncustomer_id = Oncustomer::where('openid', $request->header('openid'))->value('id');
        $data['oncustomer_id'] = $oncustomer_id;
        $data['fixfxs_id'] = $request->fxs_id;
        $data['bespeak_id'] = $request->xm_id;
        $data['customer_tel'] = $request->mobile;
        $data['customer_name'] = $request->name;
        $data['bespeak_at'] = $request->ordertime;
        $data['type'] = 1;
        $data['statu'] = 0;
        $data['is_pay'] = 0;
        $data['order_no'] = make_order_no(time());
        $data['price'] = Bespeak::where('id', $request->xm_id)->value('special');
        $data['bespeak_at'] = $request->ordertime;

        Onorder::create($data);

        return 1;

    }

//取消预约
    public function cancel_bespeak(Request $request)
    {
        $oncustomer_id = Oncustomer::where('openid', $request->header('openid'))->value('id');
        $data['order_no'] = $request->order_no;
        $data['oncustomer_id'] = $oncustomer_id;
        $data['type'] = 1;
        Onorder::where($data)->delete();
        return 1;


    }

//选择优惠券
    public function choiced_coupon(Request $request)
    {

        $pack_price = Pack::where('id', $request->PACK_id)->value('special');
        $coupon = Coupon::find($request->id);
        if ($pack_price - $coupon->all < 0) {
            return 0;
        } else {
            return json_encode(compact('coupon'));
        }

    }

    public function free_order_coupon(Request $request)
    {

        $price = $request->price;
        $coupon = Coupon::find($request->coupon_id);
        if ($price - $coupon->all < 0) {
            return 0;
        } else {
            return json_encode(compact('coupon'));
        }

    }


    public function prefer_order(Request $request)
    {

        $oncustomer_id = Oncustomer::where('openid', $request->header('openid'))->value('id');
        $pack = Pack::find($request->pack_id);

        if ($request->has('coupon_id')) {
            $coupon = Coupon::find($request->coupon_id);
            $data['coupon_id'] = $request->coupon_id;
            $data['price'] = $pack['special'] - $coupon['del'];
        } else {
            $data['price'] = $pack['special'];
        }

        $data['oncustomer_id'] = $oncustomer_id;
        $data['pack_id'] = $request->pack_id;
        $data['item_id'] = $request->item_id;


        $data['type'] = 0;
        $data['statu'] = 0;
        $data['is_pay'] = 0;
        $data['order_no'] = make_order_no(time());

        $order = Onorder::create($data);
        $order['openid'] = $request->header('openid');
//        Havecoupon::where('oncustomer_id',$oncustomer_id)->where('coupon_id',$request->coupon_id)->delete();  付钱后在执行

        $prepay_id = $this->getPrepayId($order);
        $json = $this->getJsParams($prepay_id);
        return $json;

    }


    public function getPrepayId($order)
    {
        $arr = $this->unifiedOrder($order);
        return $arr['prepay_id'];
    }

    public function unifiedOrder($order)
    {
        /**
         * 1.构建原始数据
         * 2.加入签名
         * 3.将数据转换为XML
         * 4.发送XML格式的数据到接口地址
         */
        $params = [
            'appid' => self::APPID,
            'mch_id' => self::MCHID,
            'nonce_str' => md5(time()),
            'body' => '悦时尚发型店订单支付',
            'out_trade_no' => $order['order_no'],
            'total_fee' => $order['price'] * 100,
            'spbill_create_ip' => $_SERVER['REMOTE_ADDR'],
            'notify_url' => 'https://www.mf.seleted.cn/api/notify',
            'trade_type' => 'JSAPI',
            'product_id' => $order['id'],
            'openid' => $order['openid'],
            'attach' => $order['attach'],
        ];

        $params = $this->setSign($params);
        $xmldata = $this->ArrToXml($params);
        $resdata = $this->postXml(self::UNURL, $xmldata);
        $arr = $this->XmlToArr($resdata);
        return $arr;
    }


    public function getJsParams($prepay_id)
    {

        $params = [
            'appId' => self::APPID,
            'timeStamp' => (string)time(),
            'nonceStr' => md5(time()),
            'package' => 'prepay_id=' . $prepay_id,
            'signType' => 'MD5',
//            'paySign' => $this->getSign($params)
        ];
        $params['paySign'] = $this->getSign($params);
        return json_encode($params);
    }

    //数组转xml
    public function ArrToXml($arr)
    {
        if (!is_array($arr) || count($arr) == 0) return '';

        $xml = "<xml>";
        foreach ($arr as $key => $val) {
            if (is_numeric($val)) {
                $xml .= "<" . $key . ">" . $val . "</" . $key . ">";
            } else {
                $xml .= "<" . $key . "><![CDATA[" . $val . "]]></" . $key . ">";
            }
        }
        $xml .= "</xml>";
        return $xml;
    }

    public function XmlToArr($xml)
    {
        if ($xml == '') return '';
        libxml_disable_entity_loader(true);
        $arr = json_decode(json_encode(simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA)), true);
        return $arr;
    }

    public function postXml($url, $postfields)
    {

        $ch = curl_init();
        $params[CURLOPT_URL] = $url;    //请求url地址
        $params[CURLOPT_HEADER] = false; //是否返回响应头信息
        $params[CURLOPT_RETURNTRANSFER] = true; //是否将结果返回
        $params[CURLOPT_FOLLOWLOCATION] = true; //是否重定向
        $params[CURLOPT_POST] = true;
        $params[CURLOPT_POSTFIELDS] = $postfields;
        $params[CURLOPT_SSL_VERIFYPEER] = false;
        $params[CURLOPT_SSL_VERIFYHOST] = false;
        curl_setopt_array($ch, $params); //传入curl参数
        $content = curl_exec($ch); //执行
        curl_close($ch); //关闭连接
        return $content;
    }

    //获取post过来的数据
    public function getPost()
    {
        return file_get_contents('php://input');
    }

    public function getSign($arr)
    {
        //去除空值
        $arr = array_filter($arr);
        if (isset($arr['sign'])) {
            unset($arr['sign']);
        }
        //按照键名字典排序
        ksort($arr);
        //生成url格式的字符串
        $str = $this->arrToUrl($arr) . '&key=' . self::KEY;
        return strtoupper(md5($str));
    }


    public function setSign($arr)
    {
        $arr['sign'] = $this->getSign($arr);;
        return $arr;
    }


    public function arrToUrl($arr)
    {
        return urldecode(http_build_query($arr));
    }

    public function chekSign($arr)
    {
        $sign = $this->getSign($arr);
        if ($sign == $arr['sign']) {
            return true;
        } else {
            return false;
        }
    }

//支付状态接收
    public function notify()
    {

        $xmlData = $this->getPost();

        $arr = $this->XmlToArr($xmlData);
        if ($this->chekSign($arr)) {
            if ($arr['return_code'] == 'SUCCESS' && $arr['result_code'] == 'SUCCESS') {

                $order = Order::where('order_no', $arr['out_trade_no'])->first();
                //门票
                if ($arr['total_fee'] == $order['price'] * 100 && (int)$arr['attach'] == 1) {
                    $oncustomer = Oncustomer::where('openid', $arr['openid'])->first();
                    $data['is_pay'] = 1;
                    $data['pay_at'] = date("Y-m-d H:i:s", time());

                    $item['use_price'] = $oncustomer['use_price'] + $order['price'];
                    $item['use_true_price'] = $oncustomer['use_true_price'] + $order['price'];
                    $item['is_in'] = 1;
                    $item['come_time'] = $oncustomer['come_time'] + 1;

                    $inter['oncustomer_id'] = $oncustomer['id'];
                    $inter['store_id'] = 1;
                    $inter['inter_at'] = Carbon::now();
                    $inter['date'] = Carbon::today();


                    //改变优惠券状态
                    if (isset($order['coupon_id']) && $order['coupon_id'] != '') {

                        $where['oncustomer_id'] = $oncustomer['id'];
                        $where['coupon_id'] = $order['coupon_id'];
                        $record = Havecoupon::where($where)->first();
                        $info['is_can'] = 0;
                        $record->update($info);
                    }
                    $order->update($data);  //订单状态更改
                    $oncustomer->update($item);//个人信息更改
                    OncustomerRecord::create($inter);//添加进门纪录
                    //todo:硬件开门发指令

                    $returnParams = [
                        'return_code' => 'SUCCESS',
                        'return_msg' => 'OK'
                    ];

                    echo $this->ArrToXml($returnParams);
//                    $this->openlock();
                }

                //私教
                if ($arr['total_fee'] == $order['price'] * 100 && (int)$arr['attach'] == 2) {
                    $oncustomer = Oncustomer::where('openid', $arr['openid'])->first();
                    $data['is_pay'] = 1;
                    $data['pay_at'] = date("Y-m-d H:i:s", time());

                    $item['use_price'] = $oncustomer['use_price'] + $order['price'];
                    $item['use_true_price'] = $oncustomer['use_true_price'] + $order['price'];

                    $sjorder = Sjorder::where('order_no', $arr['out_trade_no'])->first();
                    $about['is_pay'] = 1;
                    $sjorder->update($about);//修改私教订单状态
                    $order->update($data);  //订单状态更改
                    $oncustomer->update($item);//个人信息更改

                    //改变优惠券状态
                    if (isset($order['coupon_id']) && $order['coupon_id'] != '') {

                        $where['oncustomer_id'] = $oncustomer['id'];
                        $where['coupon_id'] = $order['coupon_id'];
                        $record = Havecoupon::where($where)->first();
                        $info['is_can'] = 0;
                        $record->update($info);
                    }

                    $returnParams = [
                        'return_code' => 'SUCCESS',
                        'return_msg' => 'OK'
                    ];

                    echo $this->ArrToXml($returnParams);
                }
                //充值
                if ($arr['total_fee'] == $order['price'] * 100 && $arr['attach'] == 3) {
                    $oncustomer = Oncustomer::where('openid', $arr['openid'])->first();
                    $diposit = Deposit::where('order_no', $arr['out_trade_no'])->first();
                    $data['is_pay'] = 1;
                    $data['pay_at'] = date("Y-m-d H:i:s", time());
                    $item['card_money'] = $oncustomer['card_money'] + $order['price']+$diposit['preferential'];
                    $is['is_pay'] = 1;

                    $diposit->update($is);
                    $order->update($data);  //订单状态更改
                    $oncustomer->update($item);//个人信息更改


                    $returnParams = [
                        'return_code' => 'SUCCESS',
                        'return_msg' => 'OK'
                    ];

                    echo $this->ArrToXml($returnParams);
                }

                if ($arr['total_fee'] == $order['price'] * 100 && (int)$arr['attach'] == 4) {
                    $oncustomer = Oncustomer::where('openid', $arr['openid'])->first();

                    $data['is_pay'] = 1;
                    $data['pay_at'] = date("Y-m-d H:i:s", time());

                    $item['use_price'] = $oncustomer['use_price'] + $order['price'];
                    $item['use_true_price'] = $oncustomer['use_true_price'] + $order['price'];


                    $order->update($data);  //订单状态更改
                    $oncustomer->update($item);//个人信息更改

                    //改变优惠券状态
                    if ($order['coupon_id'] && $order['coupon_id'] != '') {

                        $data['oncustomer_id'] = $oncustomer['id'];
                        $data['coupon_id'] = $order['coupon_id'];
                        $record = Havecoupon::where($data)->first();
                        $info['is_can'] = 0;
                        $record->update($info);
                    }

                    $returnParams = [
                        'return_code' => 'SUCCESS',
                        'return_msg' => 'OK'
                    ];

                    echo $this->ArrToXml($returnParams);
                }


                //开通年卡
                if ($arr['total_fee'] == $order['price'] * 100 && (int)$arr['attach'] == 5) {
                    $oncustomer = Oncustomer::where('openid', $arr['openid'])->first();
                    $plan = Memberplan::find($order['good_id']);
                    $data['is_pay'] = 1;
                    $data['pay_at'] = date("Y-m-d H:i:s", time());

                    $info['use_price'] = $oncustomer['use_price'] + $order['price'];
                    $info['use_true_price'] = $oncustomer['use_true_price'] + $order['price'];
                    $info['is_member'] = 1;
                    //没有办理过，从此刻开始增加时间,开始时间为此刻
                    if (!$oncustomer['member_end']) {
                        $info['member_end'] = Carbon::now()->addMonth($plan['month']);
                        $info['member_start'] = Carbon::now();
                        $info['can_ask_time'] = $plan['stop_time'];
                    }
                    //年卡还没有到期，在原有到期日增加时间，开始时间不变
                    if (isset($oncustomer['member_end']) && $oncustomer['member_end'] != '' && $oncustomer['member_end'] >= Carbon::now()) {
                        $info['member_end'] = Carbon::parse($oncustomer['member_end'])->addMonth($plan['month']);
                        $info['can_ask_time'] = $oncustomer['can_ask_time'] + $plan['stop_time'];

                    }
                    //年卡到期，从此刻开始增加时间，开始时间变为此刻
                    if (isset($oncustomer['member_end']) && $oncustomer['member_end'] != '' && $oncustomer['member_end'] < Carbon::now()) {
                        $info['member_end'] = Carbon::now()->addMonth($plan['month']);
                        $info['member_start'] = Carbon::now();
                        $info['can_ask_time'] = $plan['stop_time'];
                    }


                    $order->update($data);  //订单状态更改
                    $oncustomer->update($info);//个人信息更改

                    //改变优惠券状态
                    if ($order['coupon_id'] && $order['coupon_id'] != '') {

                        $data['oncustomer_id'] = $oncustomer['id'];
                        $data['coupon_id'] = $order['coupon_id'];
                        $record = Havecoupon::where($data)->first();
                        $info['is_can'] = 0;
                        $record->update($info);
                    }

                    $returnParams = [
                        'return_code' => 'SUCCESS',
                        'return_msg' => 'OK'
                    ];

                    echo $this->ArrToXml($returnParams);
                } else {
                    $returnParams = [
                        'return_code' => 'FAIL',
                    ];

                    echo $this->ArrToXml($returnParams);

                }
            }
        } else {
            $returnParams = [
                'return_code' => 'FAIL',
            ];
            echo $this->ArrToXml($returnParams);
        }

    }

//购买门票
    public function ticket_order(Request $request)
    {

        $ticket = Ticket::find($request->ticket_id);
        $oncustomer = Oncustomer::where('openid', $request->header('openid'))->with('company')->first();
        $company = Company::find($oncustomer->company_id);
        //进门纪录
        $record['oncustomer_id'] = $oncustomer['id'];
        $record['store_id'] = 1;
        $record['inter_at'] = Carbon::now();
        $record['date'] = Carbon::today();
        //个人支付
        if ($request['type'] == 1) {

            if ($request->has('coupon_id') && $request->coupon_id != '') {
                $coupon = Coupon::find($request->coupon_id);
                $data['coupon_id'] = $request->coupon_id;
                $data['price'] = $ticket['price'] * $coupon['ratio'] * 0.1;
            } else {
                $data['price'] = $ticket['price'];
            }

            $data['oncustomer_id'] = $oncustomer['id'];
            $data['oncustomer_tel'] = $oncustomer['tel'];
            $data['oncustomer_name'] = $oncustomer['name'];
            $data['type'] = 1;
            $data['store_id'] = 1;
            $data['pay_way'] = 1;
            $data['is_pay'] = 0;
            $data['number'] = 1;
            $data['name'] = '门票';
            $data['good_id'] = $request->ticket_id;
            $data['order_no'] = make_order_no(time());

            $order = Order::create($data);
            $order['openid'] = $request->header('openid');
            $order['attach'] = (string)1;

//        Havecoupon::where('oncustomer_id',$oncustomer_id)->where('coupon_id',$request->coupon_id)->delete();  回调判断后在执行

            $prepay_id = $this->getPrepayId($order);
            $json = $this->getJsParams($prepay_id);

            return $json;
            //todo::回调判断后硬件开门，订单状态修改，添加进门纪录
        }

        //员工免费 1表示员工
        if ($oncustomer['is_yuangong']==1) {
            $data['price'] = 0;
            $data['oncustomer_id'] = $oncustomer['id'];
            $data['oncustomer_tel'] = $oncustomer['tel'];
            $data['oncustomer_name'] = $oncustomer['name'];
            $data['pay_at'] = Carbon::now();
            $data['type'] = 1;
            $data['store_id'] = 1;
            $data['is_pay'] = 1;
            $data['pay_way'] = 6;
            $data['number'] = 1;
            $data['name'] = '门票';
            $data['good_id'] = $request->ticket_id;
            $data['order_no'] = make_order_no(time());


            DB::transaction(function () use ($data, $oncustomer, $ticket, $request, $record) {
                $info['card_money'] = $oncustomer['card_money'] - $data['price'];
                $info['use_price'] = $oncustomer['use_price'] + $data['price'];
                $info['use_true_price'] = $oncustomer['use_true_price'] + $data['price'];
                $info['come_time'] = $oncustomer['come_time'] + 1;
                $oncustomer->update($info);
                $order = Order::create($data);
                OncustomerRecord::create($record);
                /*if ($request->has('coupon_id')) {
                    $item['is_can'] = 0;
                    Havecoupon::where('oncustomer_id', $oncustomer['id'])->where('coupon_id', $request->coupon_id)->update($item);
                }*/


            });
            return json_encode(['tips'=>1,'msg'=>'支付成功']);

        }

        //囤票支付
        if ($request['type'] ==5 &&$request->has('hoarding_ticket_id')&& $request->hoarding_ticket_id!='') {
            $data['price'] = 0;
            $data['oncustomer_id'] = $oncustomer['id'];
            $data['oncustomer_tel'] = $oncustomer['tel'];
            $data['oncustomer_name'] = $oncustomer['name'];
            $data['pay_at'] = Carbon::now();
            $data['type'] = 1;
            $data['store_id'] = 1;
            $data['is_pay'] = 1;
            $data['pay_way'] = 5;
            $data['number'] = 1;
            $data['name'] = '门票';
            $data['good_id'] = $request->ticket_id;
            $data['order_no'] = make_order_no(time());


            DB::transaction(function () use ($data, $oncustomer, $ticket, $request, $record) {
                $info['card_money'] = $oncustomer['card_money'] - $data['price'];
                $info['use_price'] = $oncustomer['use_price'] + $data['price'];
                $info['use_true_price'] = $oncustomer['use_true_price'] + $data['price'];
                $info['come_time'] = $oncustomer['come_time'] + 1;
                $oncustomer->update($info);
                $order = Order::create($data);
                OncustomerRecord::create($record);

            });
            $hoardingInfo=HoardingTickets::where('openid',$oncustomer->openid)->where('hoarding_ticket_id',$request->hoarding_ticket_id)->first();
            //未激活，则激活
            if($hoardingInfo->is_active==0){
                $active['use_start']=Carbon::today();
                $active['use_over']=Carbon::today()->addDays($hoardingInfo->ticket_days);
                $active['is_active']=1;
                $active['tickets_used']=$hoardingInfo->tickets_used+1;
                $active['remain_tickets']=$hoardingInfo->remain_tickets-1;
                HoardingTickets::where('openid',$oncustomer->openid)->where('hoarding_ticket_id',$request->hoarding_ticket_id)->update($active);
            }else{
                //已激活，判断是否快用完了
                if($hoardingInfo->remain_tickets>1){
                    $update['tickets_used']=$hoardingInfo->tickets_used+1;
                    $update['remain_tickets']=$hoardingInfo->remain_tickets-1;
                    HoardingTickets::where('openid',$oncustomer->openid)->where('hoarding_ticket_id',$request->hoarding_ticket_id)->update($update);
                }else{
                    HoardingTickets::destroy($hoardingInfo->id);
                }

            }
            return json_encode(['tips'=>1,'msg'=>'支付成功']);

        }
        //密码错误
        /*if($request->has('password') && $request->password != $oncustomer['password']){
            return json_encode(['tips'=>11,'msg'=>'密码错误']);
        }*/
        
       //判断是否开启了免密支付
        if($oncustomer['no_password_pay']==1){
            $date=Carbon::today();
            $check=NoPasswordPay::where([['openid',$oncustomer['openid']],['paydate',$date]])->first();
            //判断今日免密支付次数是否已达5次,如果达5次，则需要输入密码
                if($check['times']<5){
                    $pay=true;
                }else{
                    if($request->has('password') && $request->password == $oncustomer['password']){
                        $pay=true;
                    }else{
                        return json_encode(['tips'=>11,'msg'=>'密码错误']);
                    }
                }

        }else{
            if($request->has('password') && $request->password == $oncustomer['password']){
                $pay=true;
            }else{
                return json_encode(['tips'=>11,'msg'=>'密码错误']);
            }
        }
        $payWhere=true;



        //余额支付
        if ($request['type'] == 2  &&  $payWhere===$pay) {

            if ($request->has('coupon_id') && $request->coupon_id != '') {
                $coupon = Coupon::find($request->coupon_id);

                $data['coupon_id'] = $request->coupon_id;
                $data['price'] = $ticket['price'] * $coupon['ratio'] * 0.1;
                if($data['price']>$oncustomer['card_money']){
                    return json_encode(['tips'=>12,'msg'=>'余额不足']);
                }

            } else {
                $data['price'] = $ticket['price'];
                if($data['price']>$oncustomer['card_money']){
                    return json_encode(['tips'=>12,'msg'=>'余额不足']);
                }
            }
            $data['oncustomer_id'] = $oncustomer['id'];
            $data['oncustomer_tel'] = $oncustomer['tel'];
            $data['oncustomer_name'] = $oncustomer['name'];
            $data['pay_at'] = Carbon::now();
            $data['type'] = 1;
            $data['store_id'] = 1;
            $data['is_pay'] = 1;
            $data['pay_way'] = 2;
            $data['number'] = 1;
//            $data['aaa'] = 1;
            $data['name'] = '门票';
            $data['good_id'] = $request->ticket_id;
            $data['order_no'] = make_order_no(time());


            DB::transaction(function () use ($data, $oncustomer, $ticket, $request, $record) {
                $info['card_money'] = $oncustomer['card_money'] - $data['price'];
                $info['use_price'] = $oncustomer['use_price'] + $data['price'];
                $info['use_true_price'] = $oncustomer['use_true_price'] + $data['price'];
                $info['come_time'] = $oncustomer['come_time'] + 1;
                $result=$oncustomer->update($info);
                if($result){
                    //修改今日免密支付次数
                    $getDate=Carbon::today();
                    $checkTimes=NoPasswordPay::where([['openid',$oncustomer['openid']],['paydate',$getDate]])->first();
                    if($checkTimes){
                        if($checkTimes['times']<5){
                            if($oncustomer['no_password_pay']==1){
                                NoPasswordPay::where([['openid',$oncustomer['openid']],['paydate',$getDate]])->update(['times'=>$checkTimes['times']+1]);
                            }

                        }
                    }else{
                        if($oncustomer['no_password_pay']==1){
                            NoPasswordPay::create(['openid'=>$oncustomer['openid'],'paydate'=>$getDate,'times'=>1]);
                        }

                    }
                }

                $order = Order::create($data);
                OncustomerRecord::create($record);
                if ($request->has('coupon_id')) {
                    $check=Havecoupon::where('oncustomer_id', $oncustomer['id'])->where('coupon_id', $request->coupon_id)->first();
                    if($check){
                        if($check['coupon_num']<=1){
                            Havecoupon::where('oncustomer_id', $oncustomer['id'])->where('coupon_id', $request->coupon_id)->delete();
                        }else{
                            $item['coupon_num'] =$check['coupon_num']-1;
                            Havecoupon::where('oncustomer_id', $oncustomer['id'])->where('coupon_id', $request->coupon_id)->update($item);
                        }
                    }

                }


            });
//            $this->openlock();
            //return 1;
            return json_encode(['tips'=>1,'msg'=>'支付成功']);


        }
        //养成金支付
        if ($request['type'] == 4 && $oncustomer['habit_money'] >= $ticket['price'] && $request->password == $oncustomer['password']) {

            if ($request->has('coupon_id') && $request->coupon_id != '') {
                $coupon = Coupon::find($request->coupon_id);

                $data['coupon_id'] = $request->coupon_id;
                $data['price'] = $ticket['price'] * $coupon['ratio'] * 0.1;

            } else {
                $data['price'] = $ticket['price'];
            }
            $data['oncustomer_id'] = $oncustomer['id'];
            $data['oncustomer_tel'] = $oncustomer['tel'];
            $data['oncustomer_name'] = $oncustomer['name'];
            $data['pay_at'] = Carbon::now();
            $data['type'] = 1;
            $data['store_id'] = 1;
            $data['is_pay'] = 1;
            $data['pay_way'] = 3;
            $data['number'] = 1;
//            $data['aaa'] = 1;
            $data['name'] = '门票';
            $data['good_id'] = $request->ticket_id;
            $data['order_no'] = make_order_no(time());

            DB::transaction(function () use ($data, $oncustomer, $ticket, $request, $record) {
                $info['habit_money'] = $oncustomer['habit_money'] - $data['price'];
                $info['use_price'] = $oncustomer['use_price'] + $data['price'];
                $info['use_true_price'] = $oncustomer['use_true_price'] + $data['price'];
                $info['come_time'] = $oncustomer['come_time'] + 1;
                $oncustomer->update($info);
                $order = Order::create($data);
                OncustomerRecord::create($record);
                if ($request->has('coupon_id')) {
                    $item['is_can'] = 0;
                    Havecoupon::where('oncustomer_id', $oncustomer['id'])->where('coupon_id', $request->coupon_id)->update($item);
                }


            });
//            $this->openlock();
            return 1;


        }
        //公司支付
        if ($request['type'] == 3 && isset($oncustomer['company']) && $oncustomer['company'] != '' &&
            $oncustomer['company']['end_at'] >= Carbon::now()  &&
            $payWhere===$pay) {
            //该公司通过公司支付且在店人数
            $inter_count = Oncustomer::where('company_id', $oncustomer['company_id'])->where('company_in', 1)->count();
            //判断是否达到限定人数
            if ($inter_count >= $oncustomer['company']['staff_number']) {
                //return 10;
                return json_encode(['tips'=>10,'msg'=>'已达限定人数']);
            }
            $data['oncustomer_id'] = $oncustomer['id'];
            $data['oncustomer_tel'] = $oncustomer['tel'];
            $data['oncustomer_name'] = $oncustomer['name'];
            $data['pay_at'] = Carbon::now();
            $data['price'] = $ticket['price'];
            //$companyInfo=Companies::where('id',$oncustomer['company_id'])->first();
            if($data['price']>$oncustomer['company']['money']){
                //return 12;
                return json_encode(['tips'=>12,'msg'=>'余额不足']);
            }
            $data['type'] = 1;
            $data['store_id'] = 1;
            $data['is_pay'] = 1;
            $data['pay_way'] = 4;
            $data['number'] = 1;
//            $data['aaa'] = 1;
            $data['name'] = '门票';
            $data['good_id'] = $request->ticket_id;
            $data['order_no'] = make_order_no(time());
            DB::transaction(function () use ($data, $oncustomer, $ticket, $record) {
                $info['money'] = $oncustomer['company']['money'] - $data['price'];
                $info['come_time'] = $oncustomer->company->come_time + 1;
                $come_time['come_time'] = $oncustomer['come_time'] + 1;
                $come_time['use_price'] = $oncustomer['use_price'] + $data['price'];
                $come_time['company_in'] = 1;
                $updateResult=$oncustomer->update($come_time);
                if($updateResult){
                    //修改今日免密支付次数
                    $getDateToday=Carbon::today();
                    $todayTimes=NoPasswordPay::where([['openid',$oncustomer['openid']],['paydate',$getDateToday]])->first();
                    if($todayTimes){
                        if($todayTimes['times']<5){
                            if($oncustomer['no_password_pay']==1){
                                $updateTimes=NoPasswordPay::where([['openid',$oncustomer['openid']],['paydate',$getDateToday]])->update(['times'=>$todayTimes['times']+1]);
                            }

                        }
                    }else{
                        if($oncustomer['no_password_pay']==1){
                            $addTimes=NoPasswordPay::create(['openid'=>$oncustomer['openid'],'paydate'=>$getDateToday,'times'=>1]);
                        }

                    }
                }

                $oncustomer->company->update($info);
                $order = Order::create($data);
                OncustomerRecord::create($record);

            });
            //todo::硬件开门
            //告诉前段，公司支付成功，开始计时
//            $this->openlock();
            //return 1;
            return json_encode(['tips'=>1,'msg'=>'支付成功']);
        }
        //公司支付


    }

//购买课程
    public function course_order(Request $request)
    {

        $format = Bespeak::find($request->format_id);

        $oncustomer = Oncustomer::where('openid', $request->header('openid'))->with('company')->first();

        if ($request['type'] == 1) {
            if ($request->has('coupon_id') && $request->coupon_id != '') {
                $coupon = Coupon::find($request->coupon_id);
                $data['coupon_id'] = $request->coupon_id;
                $data['price'] = $format['total_price'] * $coupon['ratio'] * 0.1;
            } else {
                $data['price'] = $format['total_price'];
            }
            $data['oncustomer_id'] = $oncustomer['id'];
            $data['oncustomer_tel'] = $oncustomer['tel'];
            $data['oncustomer_name'] = $oncustomer['name'];
            $data['fixfxs_id'] = $request->fixfxs_id;
            $data['type'] = 2;
            $data['store_id'] = 1;
            $data['pay_way'] = 1;
            $data['is_pay'] = 0;
            $data['number'] = 1;
            $data['name'] = $format['name'];
            $data['good_id'] = $request->format_id;
            $data['order_no'] = make_order_no(time());

            $about['price'] = $data['price'];
            $about['oncustomer_id'] = $oncustomer['id'];
            $about['oncustomer_name'] = $oncustomer['name'];
            $about['oncustomer_tel'] = $oncustomer['tel'];
            $about['bespeak_id'] = $request->format_id;
            $about['course_number'] = $format['course_number'] + $format['add_number'];
            $about['store_id'] = 1;
            $about['fixfxs_id'] = $request->fixfxs_id;
            $about['fixfxs_name'] = Fixfxs::find($request->fixfxs_id)->name;
            $about['order_no'] = $data['order_no'];


            Sjorder::create($about);
            $order = Order::create($data);
            $order['openid'] = $request->header('openid');
            $order['attach'] = (string)2;
//        Havecoupon::where('oncustomer_id',$oncustomer_id)->where('coupon_id',$request->coupon_id)->delete();  回调判断后在执行
            $prepay_id = $this->getPrepayId($order);
            $json = $this->getJsParams($prepay_id);
            return $json;
            //todo::回调判断后硬件开门，pay_at
        }
        //余额支付，如果符合免密支付条件，则免密支付
        if($oncustomer['no_password_pay']==1){
            //修改今日免密支付次数
            $date=Carbon::today();
            $check=NoPasswordPay::where([['openid',$request->header('openid')],['paydate',$date]])->first();
            if($check['times']<5){
                $update=NoPasswordPay::where([['openid',$request->header('openid')],['paydate',$date]])->update(['times'=>$check['times']+1]);
            }else{
                $add=NoPasswordPay::create(['openid'=> $request->openid,'paydate'=>$date,'times'=>1]);
            }
            $pay=true;
        }else{
            if($request->has('password') && $request->password == $oncustomer['password']){
                $pay=true;
            }else{
                $pay=false;
            }
        }
        $payWhere=true;
        if ($request['type'] == 2 && $oncustomer['card_money'] >= $format['total_price'] && $payWhere===$pay) {

            if ($request->has('coupon_id') && $request->coupon_id != '') {
                $coupon = Coupon::find($request->coupon_id);

                $data['coupon_id'] = $request->coupon_id;
                $data['price'] = $format['total_price'] * $coupon['ratio'] * 0.1;

            } else {
                $data['price'] = $format['total_price'];
            }
            $data['oncustomer_id'] = $oncustomer['id'];
            $data['oncustomer_tel'] = $oncustomer['tel'];
            $data['oncustomer_name'] = $oncustomer['name'];
            $data['pay_at'] = Carbon::now();

            $data['type'] = 2;
            $data['store_id'] = 1;
            $data['is_pay'] = 1;
            $data['pay_way'] = 2;
            $data['number'] = 1;
            $data['name'] = $format['name'];
            $data['fixfxs_id'] = $request->fixfxs_id;
            $data['good_id'] = $request->format_id;
            $data['order_no'] = make_order_no(time());

            $about['price'] = $data['price'];
            $about['oncustomer_id'] = $oncustomer['id'];
            $about['oncustomer_name'] = $oncustomer['name'];
            $about['oncustomer_tel'] = $oncustomer['tel'];
            $about['bespeak_id'] = $request->format_id;
            $about['course_number'] = $format['course_number'] + $format['add_number'];
            $about['store_id'] = 1;
            $about['fixfxs_id'] = $request->fixfxs_id;
            $about['fixfxs_name'] = Fixfxs::find($request->fixfxs_id)->name;
            $about['order_no'] = $data['order_no'];
            $about['is_pay'] = 1;


            DB::transaction(function () use ($data, $oncustomer, $format, $request, $about) {
                $info['card_money'] = $oncustomer['card_money'] - $data['price'];
                $info['use_price'] = $oncustomer['use_price'] + $data['price'];
                $info['use_true_price'] = $oncustomer['use_true_price'] + $data['price'];
                $info['is_in'] = 1;
                $oncustomer->update($info);
                Order::create($data);
                Sjorder::create($about);
                if ($request->has('coupon_id')) {
                    $item['is_can'] = 0;
                    Havecoupon::where('oncustomer_id', $oncustomer['id'])->where('coupon_id', $request->coupon_id)->update($item);
                }
            });
            return 1;


        }

        if ($request['type'] == 3 && $oncustomer['habit_money'] >= $format['total_price'] && $request->password == $oncustomer['password']) {

            if ($request->has('coupon_id') && $request->coupon_id != '') {
                $coupon = Coupon::find($request->coupon_id);

                $data['coupon_id'] = $request->coupon_id;
                $data['price'] = $format['total_price'] * $coupon['ratio'] * 0.1;

            } else {
                $data['price'] = $format['total_price'];
            }
            $data['oncustomer_id'] = $oncustomer['id'];
            $data['oncustomer_tel'] = $oncustomer['tel'];
            $data['oncustomer_name'] = $oncustomer['name'];
            $data['pay_at'] = Carbon::now();
            $data['type'] = 2;
            $data['store_id'] = 1;
            $data['is_pay'] = 1;
            $data['pay_way'] = 3;
            $data['number'] = 1;
            $data['name'] = $format['name'];
            $data['fixfxs_id'] = $request->fixfxs_id;
            $data['good_id'] = $request->format_id;
            $data['order_no'] = make_order_no(time());

            $about['price'] = $data['price'];
            $about['oncustomer_id'] = $oncustomer['id'];
            $about['oncustomer_name'] = $oncustomer['name'];
            $about['oncustomer_tel'] = $oncustomer['tel'];
            $about['bespeak_id'] = $request->format_id;
            $about['course_number'] = $format['course_number'] + $format['add_number'];
            $about['store_id'] = 1;
            $about['fixfxs_id'] = $request->fixfxs_id;
            $about['fixfxs_name'] = Fixfxs::find($request->fixfxs_id)->name;
            $about['order_no'] = $data['order_no'];
            $about['is_pay'] = 1;


            DB::transaction(function () use ($data, $oncustomer, $format, $request, $about) {
                $info['habit_money'] = $oncustomer['habit_money'] - $data['price'];
                $info['use_price'] = $oncustomer['use_price'] + $data['price'];
                $info['use_true_price'] = $oncustomer['use_true_price'] + $data['price'];
                $oncustomer->update($info);
                Order::create($data);
                Sjorder::create($about);
                if ($request->has('coupon_id')) {
                    $item['is_can'] = 0;
                    Havecoupon::where('oncustomer_id', $oncustomer['id'])->where('coupon_id', $request->coupon_id)->update($item);
                }
            });
            return 1;


        }


    }

//充值订单
    public function diposit_order(Request $request)
    {
        if($request->has('preferential')){
            $preferential=$request->preferential;
        }else{
            $preferential=0;
        }
        $price = $request->price;
        $oncustomer = Oncustomer::where('openid', $request->header('openid'))->with('company')->first();
        //个人支付
        $data['price'] = $price;
        $data['oncustomer_id'] = $oncustomer['id'];
        $data['oncustomer_tel'] = $oncustomer['tel'];
        $data['oncustomer_name'] = $oncustomer['name'];
        $data['type'] = 5;
        $data['store_id'] = 1;
        $data['pay_way'] = 1;
        $data['is_pay'] = 0;
        $data['number'] = 1;
        $data['name'] = '充值';
//             $data['good_id'] = $request->ticket_id;
        $data['order_no'] = make_order_no(time());

        $about['deposit_number'] = $price+$preferential;
        $about['contro'] = '线上充值';
        $about['type'] = 1;
        $about['store_id'] = 1;
        $about['statu'] = 0;
        $about['is_pay'] = 0;
        $about['order_no'] = $data['order_no'];
        $about['oncustomer_id'] = $oncustomer['id'];
        $about['oncustomer_name'] = $oncustomer['name'];
        $about['oncustomer_tel'] = $oncustomer['tel'];
        $about['preferential'] =$preferential;
        $about['denomination'] =$request->price;

        //生成充值记录
        Deposit::create($about);
        //成成订单
        $order = Order::create($data);
        $order['openid'] = $request->header('openid');
        //自定义参数3
        $order['attach'] = 3;

//        Havecoupon::where('oncustomer_id',$oncustomer_id)->where('coupon_id',$request->coupon_id)->delete();  回调判断后在执行

        $prepay_id = $this->getPrepayId($order);
        $json = $this->getJsParams($prepay_id);
        return $json;

        //todo:回调后修改订单状态


    }

    //商品订单
    public function good_order(Request $request)
    {

        $good = Good::find($request->good_id);

        $oncustomer = Oncustomer::where('openid', $request->header('openid'))->with('company')->first();

        if ($request['type'] == 1) {
            if ($request->has('coupon_id') && $request->coupon_id != '') {
                $coupon = Coupon::find($request->coupon_id);
                $data['coupon_id'] = $request->coupon_id;
                $data['price'] = $good['price'] * $coupon['ratio'] * 0.1 * $request->number;
            } else {
                $data['price'] = $good['price'] * $request->number;
            }
            $data['oncustomer_id'] = $oncustomer['id'];
            $data['oncustomer_tel'] = $oncustomer['tel'];
            $data['oncustomer_name'] = $oncustomer['name'];

            $data['type'] = 4;
            $data['store_id'] = 1;
            $data['pay_way'] = 1;
            $data['is_pay'] = 0;
            $data['number'] = $request->number;
            $data['name'] = $good['name'];
            $data['good_id'] = $request->good_id;
            $data['order_no'] = make_order_no(time());

//            $about['price'] = $data['price'];
//            $about['oncustomer_id'] = $oncustomer['id'];
//            $about['oncustomer_name'] = $oncustomer['name'];
//            $about['oncustomer_tel'] = $oncustomer['tel'];
//            $about['bespeak_id'] = $request->format_id;
//            $about['course_number'] = $format['course_number'] + $format['add_number'];
//            $about['store_id'] = 1;
//            $about['fixfxs_id'] = $request->fixfxs_id;
//            $about['fixfxs_name'] = Fixfxs::find($request->fixfxs_id)->name;
//            $about['order_no'] = $data['order_no'];


//            Sjorder::create($about);
            $order = Order::create($data);
            $order['openid'] = $request->header('openid');
            $order['attach'] = (string)4;
//        Havecoupon::where('oncustomer_id',$oncustomer_id)->where('coupon_id',$request->coupon_id)->delete();  回调判断后在执行
            $prepay_id = $this->getPrepayId($order);
            $json = $this->getJsParams($prepay_id);
            return $json;
            //todo::回调判断后改变订单状态，pay_at
        }

        //余额支付，如果符合免密支付条件，则免密支付
        if($oncustomer['no_password_pay']==1){
            //修改今日免密支付次数
            $date=Carbon::today();
            $check=NoPasswordPay::where([['openid',$request->header('openid')],['paydate',$date]])->first();
            if($check['times']<5){
                $update=NoPasswordPay::where([['openid',$request->header('openid')],['paydate',$date]])->update(['times'=>$check['times']+1]);
            }else{
                $add=NoPasswordPay::create(['openid'=> $request->openid,'paydate'=>$date,'times'=>1]);
            }
            $pay=true;
        }else{
            if($request->has('password') && $request->password == $oncustomer['password']){
                $pay=true;
            }else{
                $pay=false;
            }
        }
        $payWhere=true;

        if ($request['type'] == 2 && $oncustomer['card_money'] >= $good['price'] * $request->number && $payWhere===$pay) {

            if ($request->has('coupon_id') && $request->coupon_id != '') {
                $coupon = Coupon::find($request->coupon_id);

                $data['coupon_id'] = $request->coupon_id;
                $data['price'] = $good['price'] * $coupon['ratio'] * 0.1 * $request->number;

            } else {
                $data['price'] = $good['price'] * $request->number;
            }
            $data['oncustomer_id'] = $oncustomer['id'];
            $data['oncustomer_tel'] = $oncustomer['tel'];
            $data['oncustomer_name'] = $oncustomer['name'];
            $data['pay_at'] = Carbon::now();

            $data['type'] = 4;
            $data['store_id'] = 1;
            $data['is_pay'] = 1;
            $data['pay_way'] = 2;
            $data['number'] = $request->number;
            $data['name'] = $good['name'];
            $data['good_id'] = $request->good_id;
            $data['order_no'] = make_order_no(time());


            DB::transaction(function () use ($data, $oncustomer, $good, $request) {
                $info['card_money'] = $oncustomer['card_money'] - $data['price'];
                $info['use_price'] = $oncustomer['use_price'] + $data['price'];
                $info['use_true_price'] = $oncustomer['use_true_price'] + $data['price'];
                $oncustomer->update($info);
                Order::create($data);
                if ($request->has('coupon_id')) {
                    $item['is_can'] = 0;
                    Havecoupon::where('oncustomer_id', $oncustomer['id'])->where('coupon_id', $request->coupon_id)->update($item);
                }
            });
            return 1;


        }

        if ($request['type'] == 3 && $oncustomer['habit_money'] >= $good['price'] * $request->number && $request->password == $oncustomer['password']) {

            if ($request->has('coupon_id') && $request->coupon_id != '') {
                $coupon = Coupon::find($request->coupon_id);

                $data['coupon_id'] = $request->coupon_id;
                $data['price'] = $good['price'] * $coupon['ratio'] * 0.1 * $request->number;

            } else {
                $data['price'] = $good['price'] * $request->number;
            }
            $data['oncustomer_id'] = $oncustomer['id'];
            $data['oncustomer_tel'] = $oncustomer['tel'];
            $data['oncustomer_name'] = $oncustomer['name'];
            $data['pay_at'] = Carbon::now();
            $data['type'] = 4;
            $data['store_id'] = 1;
            $data['is_pay'] = 1;
            $data['pay_way'] = 3;
            $data['number'] = $request->number;
            $data['name'] = $good['name'];

            $data['good_id'] = $request->good_id;
            $data['order_no'] = make_order_no(time());


            DB::transaction(function () use ($data, $oncustomer, $good, $request) {
                $info['habit_money'] = $oncustomer['habit_money'] - $data['price'];
                $info['use_price'] = $oncustomer['use_price'] + $data['price'];
                $info['use_true_price'] = $oncustomer['use_true_price'] + $data['price'];
                $oncustomer->update($info);
                Order::create($data);

                if ($request->has('coupon_id')) {
                    $item['is_can'] = 0;
                    Havecoupon::where('oncustomer_id', $oncustomer['id'])->where('coupon_id', $request->coupon_id)->update($item);
                }
            });
            return 1;


        }


    }

    public function member_order(Request $request)
    {

        $plan = Memberplan::find($request->plan_id);

        $oncustomer = Oncustomer::where('openid', $request->header('openid'))->with('company')->first();

        if ($request['type'] == 1) {
            if ($request->has('coupon_id') && $request->coupon_id != '') {
                $coupon = Coupon::find($request->coupon_id);
                $data['coupon_id'] = $request->coupon_id;
                if ($plan['is_active'] == 0) {
                    $data['price'] = $plan['price'] * $coupon['ratio'] * 0.1;
                } else {
                    $data['price'] = $plan['active_price'] * $coupon['ratio'] * 0.1;
                }

            } else {
                if ($plan['is_active'] == 0) {
                    $data['price'] = $plan['price'];
                } else {
                    $data['price'] = $plan['active_price'];
                }
            }
            $data['oncustomer_id'] = $oncustomer['id'];
            $data['oncustomer_tel'] = $oncustomer['tel'];
            $data['oncustomer_name'] = $oncustomer['name'];
            $data['type'] = 6;
            $data['store_id'] = 1;
            $data['pay_way'] = 1;
            $data['is_pay'] = 0;
            $data['number'] = 1;
            $data['name'] = $plan['name'];
            $data['good_id'] = $request->plan_id;
            $data['order_no'] = make_order_no(time());


            $order = Order::create($data);
            $order['openid'] = $request->header('openid');
            $order['attach'] = (string)5;
//        Havecoupon::where('oncustomer_id',$oncustomer_id)->where('coupon_id',$request->coupon_id)->delete();  回调判断后在执行
            $prepay_id = $this->getPrepayId($order);
            $json = $this->getJsParams($prepay_id);
            return $json;

        }
        //余额支付，如果符合免密支付条件，则免密支付
        if($oncustomer['no_password_pay']==1){
            //修改今日免密支付次数
            $date=Carbon::today();
            $check=NoPasswordPay::where([['openid',$request->header('openid')],['paydate',$date]])->first();
            if($check['times']<5){
                $update=NoPasswordPay::where([['openid',$request->header('openid')],['paydate',$date]])->update(['times'=>$check['times']+1]);
            }else{
                $add=NoPasswordPay::create(['openid'=> $request->openid,'paydate'=>$date,'times'=>1]);
            }
            $pay=true;
        }else{
            if($request->has('password') && $request->password == $oncustomer['password']){
                $pay=true;
            }else{
                $pay=false;
            }
        }
        $payWhere=true;

        if ($request['type'] == 2 && $oncustomer['card_money'] >= $plan['price'] && $payWhere===$pay) {

            if ($request->has('coupon_id') && $request->coupon_id != '') {
                $coupon = Coupon::find($request->coupon_id);
                $data['coupon_id'] = $request->coupon_id;
                if ($plan['is_active'] == 0) {
                    $data['price'] = $plan['price'] * $coupon['ratio'] * 0.1;
                } else {
                    $data['price'] = $plan['active_price'] * $coupon['ratio'] * 0.1;
                }

            } else {
                if ($plan['is_active'] == 0) {
                    $data['price'] = $plan['price'];
                } else {
                    $data['price'] = $plan['active_price'];
                }
            }
            $data['oncustomer_id'] = $oncustomer['id'];
            $data['oncustomer_tel'] = $oncustomer['tel'];
            $data['oncustomer_name'] = $oncustomer['name'];
            $data['pay_at'] = Carbon::now();

            $data['type'] = 6;
            $data['store_id'] = 1;
            $data['is_pay'] = 1;
            $data['pay_way'] = 2;
            $data['number'] = 1;
            $data['name'] = $plan['name'];
            $data['good_id'] = $request->plan_id;
            $data['order_no'] = make_order_no(time());


            DB::transaction(function () use ($data, $oncustomer, $plan, $request) {
                $info['card_money'] = $oncustomer['card_money'] - $data['price'];
                $info['use_price'] = $oncustomer['use_price'] + $data['price'];
                $info['use_true_price'] = $oncustomer['use_true_price'] + $data['price'];
                $info['is_member'] = 1;
                //没有办理过，从此刻开始增加时间
                if (!$oncustomer['member_end']) {
                    $info['member_end'] = Carbon::now()->addMonth($plan['month']);
                    $info['member_start'] = Carbon::now();
                    $info['can_ask_time'] = $plan['stop_time'];
                }
                //年卡还没有到期，在原有到期日增加时间
                if (isset($oncustomer['member_end']) && $oncustomer['member_end'] != '' && $oncustomer['member_end'] >= Carbon::now()) {
                    $info['member_end'] = Carbon::parse($oncustomer['member_end'])->addMonth($plan['month']);
                    $info['can_ask_time'] = $oncustomer['can_ask_time'] + $plan['stop_time'];

                }
                //年卡到期，从此刻开始增加时间
                if (isset($oncustomer['member_end']) && $oncustomer['member_end'] != '' && $oncustomer['member_end'] < Carbon::now()) {
                    $info['member_end'] = Carbon::now()->addMonth($plan['month']);
                    $info['member_start'] = Carbon::now();
                    $info['can_ask_time'] = $plan['stop_time'];

                }
                //n


                $oncustomer->update($info);
                Order::create($data);

                if ($request->has('coupon_id')) {
                    $item['is_can'] = 0;
                    Havecoupon::where('oncustomer_id', $oncustomer['id'])->where('coupon_id', $request->coupon_id)->update($item);
                }
            });
            return 1;


        }

        if ($request['type'] == 3 && $oncustomer['habit_money'] >= $plan['price'] && $request->password == $oncustomer['password']) {

            if ($request->has('coupon_id') && $request->coupon_id != '') {
                $coupon = Coupon::find($request->coupon_id);
                $data['coupon_id'] = $request->coupon_id;
                if ($plan['is_active'] == 0) {
                    $data['price'] = $plan['price'] * $coupon['ratio'] * 0.1;
                } else {
                    $data['price'] = $plan['active_price'] * $coupon['ratio'] * 0.1;
                }

            } else {
                if ($plan['is_active'] == 0) {
                    $data['price'] = $plan['price'];
                } else {
                    $data['price'] = $plan['active_price'];
                }
            }
            $data['oncustomer_id'] = $oncustomer['id'];
            $data['oncustomer_tel'] = $oncustomer['tel'];
            $data['oncustomer_name'] = $oncustomer['name'];
            $data['pay_at'] = Carbon::now();
            $data['type'] = 6;
            $data['store_id'] = 1;
            $data['is_pay'] = 1;
            $data['pay_way'] = 3;
            $data['number'] = 1;
            $data['name'] = $plan['name'];

            $data['good_id'] = $request->plan_id;
            $data['order_no'] = make_order_no(time());


            DB::transaction(function () use ($data, $oncustomer, $plan, $request) {
                $info['habit_money'] = $oncustomer['habit_money'] - $data['price'];
                $info['use_price'] = $oncustomer['use_price'] + $data['price'];
                $info['use_true_price'] = $oncustomer['use_true_price'] + $data['price'];
                $info['is_member'] = 1;
                //没有办过年卡，开始，结束时间都要记录,可暂停次数为年卡的可暂停次数
                if (!$oncustomer['member_end']) {
                    $info['member_end'] = Carbon::now()->addMonth($plan['month']);
                    $info['member_start'] = Carbon::now();
                    $info['can_ask_time'] = $plan['stop_time'];
                }
                //年卡还没有到期，在原有到期日增加时间，开始时间不变，可暂停次数为年卡的可暂停次数+会员原有的可暂停次数
                if (isset($oncustomer['member_end']) && $oncustomer['member_end'] != '' && $oncustomer['member_end'] >= Carbon::now()) {
                    $info['member_end'] = Carbon::parse($oncustomer['member_end'])->addMonth($plan['month']);
                    $info['can_ask_time'] = $oncustomer['can_ask_time'] + $plan['stop_time'];
                }
                //年卡到期，从此刻开始增加时间,重新记录开始时间，可暂停次数为年卡的可暂停次数
                if (isset($oncustomer['member_end']) && $oncustomer['member_end'] != '' && $oncustomer['member_end'] < Carbon::now()) {
                    $info['member_end'] = Carbon::now()->addMonth($plan['month']);
                    $info['member_start'] = Carbon::now();
                    $info['can_ask_time'] = $plan['stop_time'];

                }

                $oncustomer->update($info);
                Order::create($data);

                if ($request->has('coupon_id')) {
                    $item['is_can'] = 0;
                    Havecoupon::where('oncustomer_id', $oncustomer['id'])->where('coupon_id', $request->coupon_id)->update($item);
                }
            });
            return 1;


        }

    }


//注册锁到服务商
    public function postlock()
    {
        define('A', 'wmj_Y90nJvBnXee');
        define('S', 'hWNLVma7WFvqV6SGKlCGMIL2iAlaOx9S');
//        $lock_sn = 'WMJ16882494';
        $lock_sn = 'WMJ16882497';

        $postlock = $this->httpPost('https://www.wmj.com.cn/api/postlock.html?appid=' . A . '&appsecret=' . S, $lock_sn);
        $postlock = trim($postlock, "\xEF\xBB\xBF"); //去除BOM头
        print_r(json_decode($postlock, true));
    }

//执行开门
    public function openlock(Request $request)
    {
        $oncustomer = Oncustomer::where('openid', $request->header('openid'))->with('company')->first();
        //男开门
        if ($oncustomer['sex'] == 1) {
            define('A', 'wmj_Y90nJvBnXee');
            define('S', 'hWNLVma7WFvqV6SGKlCGMIL2iAlaOx9S');
            $lock_sn = 'WMJ16882494';
            $openlock = $this->httpPost('https://www.wmj.com.cn/api/openlock.html?appid=' . A . '&appsecret=' . S, $lock_sn);
            $openlock = trim($openlock, "\xEF\xBB\xBF"); //去除BOM头
            return $openlock;
            //return json_encode($openlock);
            //print_r(json_decode($openlock, true));
        }
        //女开门
        if ($oncustomer['sex'] == 0) {
            define('A', 'wmj_Y90nJvBnXee');
            define('S', 'hWNLVma7WFvqV6SGKlCGMIL2iAlaOx9S');
            $lock_sn = 'WMJ16882497';
            $openlock = $this->httpPost('https://www.wmj.com.cn/api/openlock.html?appid=' . A . '&appsecret=' . S, $lock_sn);
            $openlock = trim($openlock, "\xEF\xBB\xBF"); //去除BOM头
            return $openlock;
            //return json_encode($openlock);
            //print_r(json_decode($openlock, true));
        }

    }


//手机验证码封装
    public function request($accessKeyId, $accessKeySecret, $domain, $params, $security = false)
    {
        $apiParams = array_merge(array(
            "SignatureMethod" => "HMAC-SHA1",
            "SignatureNonce" => uniqid(mt_rand(0, 0xffff), true),
            "SignatureVersion" => "1.0",
            "AccessKeyId" => $accessKeyId,
            "Timestamp" => gmdate("Y-m-d\TH:i:s\Z"),
            "Format" => "JSON",
        ), $params);
        ksort($apiParams);

        $sortedQueryStringTmp = "";
        foreach ($apiParams as $key => $value) {
            $sortedQueryStringTmp .= "&" . $this->encode($key) . "=" . $this->encode($value);
        }

        $stringToSign = "GET&%2F&" . $this->encode(substr($sortedQueryStringTmp, 1));

        $sign = base64_encode(hash_hmac("sha1", $stringToSign, $accessKeySecret . "&", true));

        $signature = $this->encode($sign);

        $url = ($security ? 'https' : 'http') . "://{$domain}/?Signature={$signature}{$sortedQueryStringTmp}";

        try {
            $content = $this->fetchContent($url);
            return json_decode($content);
        } catch (\Exception $e) {
            return false;
        }
    }

//手机验证码封装
    private function encode($str)
    {
        $res = urlencode($str);
        $res = preg_replace("/\+/", "%20", $res);
        $res = preg_replace("/\*/", "%2A", $res);
        $res = preg_replace("/%7E/", "~", $res);
        return $res;
    }

//手机验证码封装
    private function fetchContent($url)
    {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_TIMEOUT, 5);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_HTTPHEADER, array(
            "x-sdk-client" => "php/2.0.0"
        ));

        if (substr($url, 0, 5) == 'https') {
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
            curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        }

        $rtn = curl_exec($ch);

        if ($rtn === false) {
            trigger_error("[CURL_" . curl_errno($ch) . "]: " . curl_error($ch), E_USER_ERROR);
        }
        curl_close($ch);

        return $rtn;
    }

    /*
     *DEMO -- httpPost函数
     */
    function httpPost($url, $str)
    {
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_TIMEOUT, 30);
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
        curl_setopt($curl, CURLOPT_CUSTOMREQUEST, 'POST');
        curl_setopt($curl, CURLOPT_POSTFIELDS, $str);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, TRUE);
        curl_setopt($curl, CURLOPT_HTTPHEADER, array(
                'Content-Type: application/json',
                'Content-Length: ' . strlen($str))
        );
        $res = curl_exec($curl);
        curl_close($curl);

        return $res;
    }

    /*
     * AES加密 -- 加密采用128位CBC模式加密
     */
    function aesEncrypt($value, $key)
    {
        $padSize = 16 - (strlen($value) % 16);
        $value = $value . str_repeat(chr($padSize), $padSize);
        $output = mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $key, $value, MCRYPT_MODE_CBC, str_repeat(chr(0), 16));

        return base64_encode($output);
    }


    //小程序充值面额显示
    public function recharge(){
        $rechargeArr=Recharge::get();
        return json_encode(['tips'=>200,'rechargeArr'=>$rechargeArr]);
    }


    //扫码出站小结报告评论
    public function comment(Request $request){
        $oncustomer = Oncustomer::where('openid', $request->header('openid'))->with('company')->first();
        $comment= Comment::create(['openid'=>$oncustomer['openid'],'stars'=>$request->stars,'comment'=>$request->comment]);
        if($comment){
            return json_encode(['tips'=>200,'msg'=>'评价成功']);
        }else{
            return json_encode(['tips'=>204,'msg'=>'评价失败']);
        }

    }

    //检验是否可以使用免密支付
    public function noPasswordPay(Request $request){
        $ocustomer= Oncustomer::where('openid',$request->header('openid'))->with('company')->first();
        $date=Carbon::today();
        if($ocustomer['no_password_pay']==1){
            $check=NoPasswordPay::where([['openid',$ocustomer['openid']],['paydate',$date]])->first();
            if($check['times']>=5 || $request->money>500){
                return json_encode(['tips'=>'204','msg'=>'不满足免密支付条件']);
            }else{
                return json_encode(['tips'=>'200','msg'=>'满足免密支付条件']);
            }
        }else{
            return json_encode(['tips'=>'204','msg'=>'不满足免密支付条件']);
        }

    }

    //修改免密支付状态
    public function updateNoPasswordPay(Request $request){
        $status=Oncustomer::where('openid',$request->header('openid'))->update(['no_password_pay'=>$request->noPasswordPay]);
        if($status){
            if($request->noPasswordPay==1){
                return json_encode(['tips'=>200,'msg'=>'免密支付已开启']);
            }else{
                return json_encode(['tips'=>201,'msg'=>'免密支付已关闭']);
            }
        }else{
            return json_encode(['tips'=>204,'msg'=>'修改失败']);
        }
    }

    //设置密码接口
    public function setPassword(Request $request){
        if($request->password==$request->repassword){
            $status=Oncustomer::where('openid',$request->header('openid'))
                ->update(['password'=>$request->password]);
            if($status){
                return json_encode(['tips'=>200,'msg'=>'密码设置成功']);
            }
        }else{
            return json_encode(['tips'=>204,'msg'=>'两次密码输入不一致']);
        }
    }

    //保存充值记录
    public function saveRechargeRecords(Request $request){
        $date=Carbon::now();
        $ocustomer= Oncustomer::where('openid',$request->header('openid'))->with('company')->first();
        $result=RechargeRecord::create(['openid'=>$ocustomer['openid'],'denomination'=>$request->denomination,'preferential'=>$request->preferential,'date'=>$date,'status'=>$request->status]);
        if($result){
            return json_encode(['tips'=>200,'msg'=>'充值记录保存成功']);
        }
    }

    //查询充值记录
    public function getRechargeRecords(Request $request){
        $ocustomer= Oncustomer::where('openid',$request->header('openid'))->with('company')->first();
        $recordArr=RechargeRecord::where('openid',$ocustomer['openid'])->offset(10*$request->slide)->limit(10)->orderBy('date','desc')->get();
        if($recordArr){
            return json_encode(['tips'=>200,'msg'=>'记录查询成功','recordArr'=>$recordArr]);
        }else{
            return json_encode(['tips'=>201,'msg'=>'暂无数据']);
        }
    }

//显示免密支付状态
    public function noPasswordPayStatus(Request $request){
        $ocustomer= Oncustomer::where('openid',$request->header('openid'))->with('company')->first();
        if($ocustomer['no_password_pay']==1){
            return json_encode(['tips'=>200,'msg'=>'免密支付已开启']);

        }else{
            return json_encode(['tips'=>204,'msg'=>'免密支付已关闭']);
        }


    }

    //我的订单(1-门票)
    public function myOrder(Request $request){
        $oncustomer = Oncustomer::where('openid', $request->header('openid'))->first();
        $id = $oncustomer['id'];
        $orderArr=Order::where([['oncustomer_id',$id],['type',1]])->orderBy('pay_at','desc')->get();
        if($orderArr){
            return json_encode(['tips'=>200,'msg'=>'订单查询成功','orderArr'=>$orderArr]);
        }
    }

    //检验密码是否已设置
    public function passwordIsSet(Request $request){
        $oncustomer = Oncustomer::where('openid', $request->header('openid'))->first();
        if($oncustomer['password']!='0'){
            return json_encode(['tips'=>200,'msg'=>'密码已设置']);
        }else{
            return json_encode(['tips'=>204,'msg'=>'密码未设置']);
        }

    }

    //企业认证（显示同时可在店人数）
    public function rzPeople(Request $request){
        $companies=Companies::where('name',$request->companyName)->first();
        if($companies){
            return json_encode(['tips'=>'200','msg'=>'查询成功','companyInfo'=>$companies]);
        }else{
            return json_encode(['tips'=>'204','msg'=>'企业名称有误']);
        }
    }

    //检验用户是否绑定企业
    public function isrz(Request $request){
        $oncustomer= Oncustomer::where('openid',$request->header('openid'))->with('company')->first();
        if($oncustomer['company_id']!=0){
            return json_encode(['tips'=>200,'msg'=>'已认证企业']);
        }else{
            return json_encode(['tips'=>204,'msg'=>'未认证企业']);
        }
    }

    //查询充值记录（新增）
    public function rechargeRecords(Request $request){
        $oncustomer=Oncustomer::where('openid',$request->header('openid'))->with('company')->first();
        $recordsArr=Deposit::where('oncustomer_id',$oncustomer['id'])->offset(10*$request->slide)->limit(10)->orderBy('created_at','desc')->get();;
        if($recordsArr){
            return json_encode(['tips'=>200,'msg'=>'充值记录查询成功','recordsArr'=>$recordsArr]);
        }else{
            return json_encode(['tips'=>201,'msg'=>'无充值记录']);
        }
    }


    //展示囤票说明信息
    public function hoardingInstruction(Request $request){
        $hoardingInfo=HoardingInstruction::get();
        $hoardingInfoArr=json_decode(json_encode($hoardingInfo),true);
        if($hoardingInfoArr){
            return json_encode(['tips'=>200,'msg'=>'囤票活动信息查询成功','hoardingInfo'=>$hoardingInfo]);
        }else{
            return json_encode(['tips'=>201,'msg'=>'活动已结束，更多活动我们下期不见不散...']);
        }
    }

    //囤票活动列表
    public function hoardingList(Request $request){
        $myHoarding_ids=HoardingTickets::where('openid',$request->header('openid'))->where('total_tickets','>',0)->pluck('hoarding_ticket_id')->toArray();
        $myHoardingArr=HoardingTickets::where('openid',$request->header('openid'))->where('total_tickets','>',0)->with('hoarding')->get();
        $otherHoarding=Hoarding::whereNotIn('id',$myHoarding_ids)->where('is_over','=',1)->where('start_time','<=',Carbon::now())->where('end_time','>=',Carbon::now())->get();
        return json_encode(['tips'=>200,'myHoardingArr'=>$myHoardingArr,'otherHoarding'=>$otherHoarding]);
    }


    //用户参加囤票活动支付
    public function customerHoarding(Request $request){
        $oncustomer = Oncustomer::where('openid', $request->header('openid'))->with('company')->first();
        $data['price'] = $request->discount_price;
        $data['oncustomer_id'] = $oncustomer['id'];
        $data['oncustomer_tel'] = $oncustomer['tel'];
        $data['oncustomer_name'] = $oncustomer['name'];
        $data['type'] = 1;
        $data['store_id'] = 1;
        $data['pay_way'] = 1;
        $data['is_pay'] = 0;
        $data['number'] = 1;
        $data['name'] = '囤票';
        $data['good_id'] = $request->hoarding_id;
        $data['order_no'] = make_order_no(time());
        $order = Order::create($data);
        $order['openid'] = $request->header('openid');
        $order['attach'] = (string)1;
        $prepay_id = $this->getPrepayId($order);
        $json = $this->getJsParams($prepay_id);


        /*//添加囤票活动信息
        $hoardingInfo=Hoarding::where('id',$request->hoarding_id)->first();
        $hoarding['oncustomer_id']=$oncustomer->id;
        $hoarding['openid']=$oncustomer->openid;
        $hoarding['hoarding_ticket_id']=$hoardingInfo->id;
        $hoarding['total_tickets']=$hoardingInfo->ticket_total;
        $hoarding['remain_tickets']=$hoardingInfo->ticket_total;
        $hoarding['ticket_days']=$hoardingInfo->days;
        $myHoardingCheck=HoardingTickets::where('oncustomer_id',$oncustomer->id)->where('hoarding_ticket_id',$request->hoarding_id)->first();
        $hoardingCheckArr=json_decode(json_encode($myHoardingCheck),true);
        if(empty($hoardingCheckArr)){
            HoardingTickets::Create($hoarding);
        }*/

        return $json;
        //todo::回调判断后硬件开门，订单状态修改，添加进门纪录

    }

    //支付成功之后添加囤票活动
    public function  addHoarding(Request $request){
        $oncustomer = Oncustomer::where('openid', $request->header('openid'))->with('company')->first();
        //添加囤票活动信息
        $hoardingInfo=Hoarding::where('id',$request->hoarding_id)->first();
        $hoarding['oncustomer_id']=$oncustomer->id;
        $hoarding['openid']=$oncustomer->openid;
        $hoarding['hoarding_ticket_id']=$hoardingInfo->id;
        $hoarding['total_tickets']=$hoardingInfo->ticket_total;
        $hoarding['remain_tickets']=$hoardingInfo->ticket_total;
        $hoarding['ticket_days']=$hoardingInfo->days;
        $myHoardingCheck=HoardingTickets::where('oncustomer_id',$oncustomer->id)->where('hoarding_ticket_id',$request->hoarding_id)->first();
        $hoardingCheckArr=json_decode(json_encode($myHoardingCheck),true);
        if(empty($hoardingCheckArr)){
            HoardingTickets::Create($hoarding);
            return json_encode(['tips'=>'200','msg'=>'活动参加成功']);
        }
    }


    //检验是否参加了囤票活动
    public function checkHoarding(Request $request){
        $myHoardingObj=HoardingTickets::where('openid',$request->header('openid'))->where('remain_tickets','>',0)->orderBy('use_over','asc')->get();
        $myHoardingArr=json_decode(json_encode($myHoardingObj),true);
        if($myHoardingArr){
            return json_encode(['tips'=>200,'myHoardingArr'=>$myHoardingObj]);
        }else{
            return json_encode(['tips'=>201,'msg'=>'未参加囤票活动']);
        }
    }

    //检验是否是员工
    public function isStaff(Request $request){
        $oncustomer = Oncustomer::where('openid', $request->header('openid'))->with('company')->first();
        if($oncustomer->is_yuangong==1){
            return json_encode(['tips'=>200,'msg'=>'员工']);
        }else{
            return json_encode(['tips'=>204,'msg'=>'非员工']);
        }

    }

}
